![](/img/trans.png)
[英]Python Multiprocessing - 'Queue' object has no attribute 'task_done' / 'join'
[英]when I call join() in a queue, and task_done() has done, but this program still running
我編寫此代碼來在帶線程的Python中練習隊列。 當count為10或不是大整數時。 它可以正常運行,但是當count為1000時,此代碼無法停止,或者有時它結束了,但是隊列仍然不為空。 我不知道該如何解決。 請幫忙。
import threading
import queue
import random
import time
class Creater(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
global count
while count < 1000:
print(threading.current_thread().name, 'is running==', count,
'==times')
inputQueue()
count += 1
class Consumer(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
while not q.empty():
data = outQueue()
print(threading.current_thread().name, 'get a data:', data)
print('queue still has', q.qsize())
q.task_done()
def inputQueue():
global q
q.put(random.randint(0, 1000))
def outQueue():
data = q.get()
return data
count = 0
q = queue.Queue()
creater = Creater('creater')
consumer = Consumer('consumer')
startFlag = time.time()
creater.start()
consumer.start()
creater.join()
q.join()
spendTime = time.time() - startFlag
print('now Queue size:', q.qsize())
print('creater total run', count, 'times')
print('Finished in', spendTime)
結果有時是這樣的: 在此處輸入圖片描述
當我在終端中鍵入ctrl + c時,它顯示了一些錯誤信息,如下所示:
Traceback (most recent call last):
File "xxx.py", line 57, in <module>
q.join()
File "/home/everglow/anaconda3/lib/python3.6/queue.py", line 83, in join
self.all_tasks_done.wait()
File "/home/everglow/anaconda3/lib/python3.6/threading.py", line 295, in wait
waiter.acquire()
KeyboardInterrupt
現在,我想可能是task_done()
無法調用q.join()
,因此,主線程始終在等待。 但我不知道這個想法是對還是錯。 而且我不知道如何解決。
您的使用者循環while not q.empty():
如果使用者設法暫時清空隊列,即使創建者仍在運行,並且隨后將更多項目放在隊列中,有時消費者循環也會結束。 因此,您應該找到另一種方法來結束循環,例如計算消耗的項目數並在達到1000時結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.