首页 > 解决方案 > python线程:无限循环,直到条件不起作用

问题描述

我正在尝试制作一个多线程 python 程序,该程序不断循环遍历队列对象,直到满足条件。我有一个问题和另一个问题。问题是,在满足条件之后,一些线程仍然运行。这是我初始化线程的方法:

for i in range(0, number_of_threads):
    print("Created thread: "+ str(i))
    t = threading.Thread(target=loopThrough)
    #t.daemon = True
    t.start()
    threads[i] = t
    time.sleep(1)

这有效,并允许所有线程调用该函数。这是函数loopThrough:

def loopThrough():
    global found
    global word_queue
    while not found:
        if word_queue.empty():
            word_queue = buildQ()
            print("Built queue because it was empty")
        word = word_queue.get()
        if word == "happy":
            check(word)

检查函数(在 loopThrough 之前定义)

def check(word):
    global found
    found = True
    print(len(word))

这是一种简化,因为实际的标准/等是不敬的且冗长的。这是我的问题。当我调用 check 函数时,我将 found 标志设置为 true,因此它不再循环。但是,其他线程仍然循环。我理想中想要做的是杀死每个线程,并使用主线程调用检查函数。

最后,我还有一个担心。我想知道如何制作一个队列对象,该对象只需将刚刚获取的对象移动到队列的末尾。我不认为建立这样的队列是有效的。

标签: pythonmultithreading

解决方案


推荐阅读