0
我有一个脚本,遵循本示例相同的逻辑。 基本上我插入物品到一个全局队列中,并用while循环产生线程,该循环从队列中获取,并且调用task_done。python线程与同步队列
如果我的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
任何想法的作品的人吗?
实例教程:HTTP://inventwithpython.com/blog/2013/04/22/multithreaded-python-tutorial-with-threadworms/ –
线程池是另一种可能的解决方案。您目前的代码似乎是对同一逻辑的粗略重新实现。 –