linux - 关于python中的Queue与daemon进程?
PHPz
PHPz 2017-04-18 09:47:47
0
1
462

https://docs.python.org/2.7/library/queue.html

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

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

上面这个例子中,同时设置q.join()和t.daemon = True是不是自相矛盾?设置q.join()的话也就是说要等Queue中所有thread发送task_done信号,也就是说要让Queue里面的所有thread全部执行完才继续执行下一步。既然这样的话还设置t.daemon = True干什么呢?t.daemon=True的目的不是让守护进程在后台执行吗?

Setting daemon to True will let the main thread exit even though thworkers are blocking

q.join() Causes the main thread to wait for the queue to finish processing all the tasks

PHPz
PHPz

学习是最好的投资!

全部回覆(1)
PHPzhong

t.daemon=True的目的不是讓守護程式在背景執行嗎?

不是。

首先,它不是進程。

其次,「後台」是一個作業控制的術語(命令列 shell 基本上都會實現的功能;其它程式基本上不理會),就算你這裡使用的是多進程,也不適用於你的場景。

最後,這裡的設定有點多餘。但也僅僅是「有點」而已。

多執行緒是件不容易弄對的事情。信號是另一件。兩件加一起,你的Python 進程不聽話啦~(Python 裡,訊號只會遞交給主執行緒處理。主執行緒收到訊號決定退出,但非daemon 進程不主動退出的話,進程就會掛在那裡。所以我寫多線爬蟲什麼的時候統一daemon = True,好Ctrl-C 的時候能快速停下來。

對了,大約一兩個月之前,python-cn 列表有討論過 Python daemon 線程的話題,想深入了解的話你可以去圍觀一下。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板