python守护线程错误 退出子线程_请问用python里threading和queue模块来写多线程程序,子线程是如何结束的?...
import queue
import threading
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
job = self.queue.get()
self.do_task(job)
# 如在這里加上
# If self.queue.empty():
# break
def do_task(self, task):
print ('doing task{}'.format(task))
self.queue.task_done()
def producer(tasks):
mqueue = queue.Queue()
# populate queue with tasks
for task in tasks:
mqueue.put(task)
# create 6 threads and pass the queue as its argument
for i in range(6):
mythread = Consumer(mqueue)
mythread.daemon = True # 如把這句注釋掉
mythread.start()
# wait for the queue to finish
mqueue.join()
print ('all tasks completed')
if __name__ == "__main__":
tasks = 'A B C D E F'.split()
producer(tasks)
關(guān)于這段代碼中mythread.daemaon = True這句,書上解釋大致是要創(chuàng)建一個守護線程池,以便所有的線程執(zhí)行完以后可以把控制權(quán)交給main函數(shù),要是把這行注釋掉main函數(shù)就結(jié)束不了。如果沒有創(chuàng)建守護線程就要自己跟蹤所有的線程以在主程序退出前通知他們結(jié)束。
我把這行注釋掉運行了一下發(fā)現(xiàn)確實結(jié)束不了,始終執(zhí)行不到print('all tasks completed')這句。我就想是不是可以像書上說的一樣自己跟蹤子線程,讓他結(jié)束。于是我就嘗試在Consumer這個類的run函數(shù)里加了個一個判斷,當隊列為空時就跳出循環(huán),一跑發(fā)現(xiàn)然而這并沒有什么卵用……主程序還是不能執(zhí)行完。
在此請教各位老師,我應該怎么控制子線程結(jié)束,以使主程序執(zhí)行完,又或者說自己跟蹤子線程是怎么個跟蹤法?非常感謝!
總結(jié)
以上是生活随笔為你收集整理的python守护线程错误 退出子线程_请问用python里threading和queue模块来写多线程程序,子线程是如何结束的?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 持续记函数
- 下一篇: python解释器有哪几种_Python