[問題] 請教 threading.Condition 詳解已刪文
第一次來到貴版,拜碼頭 <(_ _)>
大家好,最近有需要寫多工
我知道 GIL 的問題,但實測結果對我不構成困擾
所以我們還是回歸到單純的語意上來探討多工
在網路上我找到這個範例程式,po 程式的網友有解釋
但我個人還是想要一些詳解
-------------------------
import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s', )
def consumer(cv: threading.Condition):
with cv:
logging.debug('Consumer thread started ...')
logging.debug('Consumer waiting ...')
cv.wait()
logging.debug('Consumer consumed the resource')
def producer(cv: threading.Condition):
logging.debug('Producer thread started ...')
with cv:
logging.debug('Making resource available')
logging.debug('Notifying to all consumers')
cv.notify()
if __name__ == '__main__':
condition = threading.Condition()
cs1 = threading.Thread(name='consumer1', target=consumer, args=(condition,))
cs2 = threading.Thread(name='consumer2', target=consumer, args=(condition,))
pd = threading.Thread(name='producer', target=producer, args=(condition,))
cs1.start()
time.sleep(2)
cs2.start()
time.sleep(2)
pd.start()
------------------------
大家可以拿這個問題上網 google 就發現很多人 po 這個範例
但有點小差別 (修文中)
比如有人 po 這樣
with cv:
logging.debug('Consumer waiting ...')
cv.acquire()
cv.wait()
logging.debug('Consumer consumed the resource')
cv.release()
經測試,with cv 本身就具有範圍內 acquire & release 的作用
所以又寫 with,又寫 acquire & release 來包圍
我個人是覺得重覆了,沒必要 (求附議)
再來我真正想問的問題是,從前我是 win/VC 下的工程師
我學過 event, 它有 signal 觀念
當時看翻譯書就很辛苦
說是訊號化就可以繼續執行,未訊號化就不可以(或者反過來)
等我看到原文仍是傻眼,真的是 signal
直覺這是要師父點破的一關,不然這種名詞好生硬
最近看到這類元件在網路上用'阻塞'一詞,也大概可以理解(還是很生硬)
所以我覺得在網路討論,大家集思廣益,應該比看一本書好
這次學到 python 這裡,用的是 wait & notify 這對指令,感覺也挺熟悉
A thread 下 wait, B thread 下 notify,然後 a thread 就會動
以前學過這個,不難 (好像在 java 學到的)
但為什麼又要多包一個 acquire & release?
就這點來說我無法理解這樣的設計有何優點
當然我大可把程式寫成
with cv
cv.wait
把包圍範圍弄到最小,那就和我以前學的極為相似
只是我覺得一個指令被創造出來,總有它的精髓,它要表達的語意
請問我這樣做是錯過了什麼?
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.216.170.239 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1589491365.A.FB8.html
※ 編輯: HuangJC (49.216.170.239 臺灣), 05/15/2020 05:23:41
※ 編輯: HuangJC (49.216.170.239 臺灣), 05/15/2020 05:33:23
Python 近期熱門文章
PTT數位生活區 即時熱門文章