python 带同步队列的线程

python threading with sync queue

我有一个脚本遵循此示例中的相同逻辑。 基本上我将项目插入全局队列并使用 while 循环生成线程,该循环从队列中获取项目和调用 task_done.

如果我的 while 循环正在检查队列是否为空,我可以让线程加入,但我想尝试并入一个我可以设置自己退出循环的标志。当我尝试这样做时,永远加入线程块。

这是不加入线程的非工作示例:

import threading
import queue

class Mythread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.signal = False
    def run(self):
       global queue
       while not self.signal:
           item = q.get()
           print(item)
           q.task_done()
    def stop(self):
       self.signal = True

q = queue.Queue
for i in range(5000):
   q.put(i)

threads = []
for i in range(2):
    t = Mythread()
    threads.append(t)

for t in threads:
    t.start()
q.join()

for t in threads:
    print(t.signal)   <---- False
    t.stop()             
    print(t.signal)   <---- True
    t.join()          <---- Blocks forever

这是使用空队列工作的

import threading
import queue

class Mythread(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        global queue
        while not q.empty():
            item = q.get()
            print(item)
            q.task_done()

q = queue.Queue
for i in range(5000):
   q.put(i)

threads = []
for i in range(2):
    t = Mythread()
    threads.append(t)

for t in threads:
    t.start()

q.join()

for t in threads:
    t.join()          <---- Works fine
    print(t.is_alive())   <--- returns False

有什么想法吗?

q.get 块,因此它不会达到您的 while 条件