问题描述
Python的新手,试图理解多线程.这是来自队列
New to python and trying to understand multi-threading. Here's an example from python documentation on Queue
一生中,我不明白这个例子是如何工作的.在worker()函数中,有一个无限循环.工人如何知道何时摆脱困境?似乎没有破坏条件.
For the heck of my life, I don't understand how this example is working. In the worker() function, there's an infinite loop. How does the worker know when to get out of the loop? There seems to be no breaking condition.
最后,联接到底在做什么?我不应该加入线程吗?
And what exactly is the join doing at the end? Shouldn't I be joining the threads instead?
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
还有另一个问题,何时应使用多线程,何时应使用多处理?
Also another question, When should multithreading be used and when should multiprocessing be used?
推荐答案
是的.你是对的. worker
将永远运行.但是,由于队列只有有限数量的项目,最终worker
将在q.get()
处永久阻塞(因为队列中将没有更多项目).此时,worker
仍在运行并不重要. q.join()
阻塞,直到队列计数下降到0(每当工作线程调用q.task_done
时,计数下降1).之后,程序结束.无限阻塞的线程与其创建者一同消亡.
Yup. You're right. worker
will run forever. However since Queue only has a finite number of items, eventually worker
will permanently block at q.get()
(Since there will be no more items in the queue). At this point, it's inconsequential that worker
is still running. q.join()
blocks until the Queue count drops to 0 (whenever the worker thread calls q.task_done
, the count drops by 1). After that, the program ends. And the infinitely blocking thread dies with it's creator.
这篇关于基本的python多线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!