forgiveness than permission,EAFP)」(涵蓋於前面的「錯誤檢查策略」)
的一個良好實例。由於多執行緒,
q
的每個非變動方法(
empty
、
full
、
qsize
)都只能是諮詢式的。當其他的某個執行緒開始執行,並變動了
q
,
那麼在一個執行緒從非變動方法取得資訊的那個時刻到該執行緒依據那個
資訊採取行動的時刻之間,事情可能發生了變化。因此仰賴「跳躍前先看
情況(look before you leap,LBYL)」慣用語是沒用的,而試著用鎖修補
事情則是大大地白費力氣。單純避免脆弱的LBYL 程式碼,例如:
if q.empty():
print('no work to perform')
else:
x = q.get_nowait()
work_on(x)
並改用較簡單且更為穩健的EAFP 做法:
try:
x = q.get_nowait()
except queue.Empty:
print('no work to perform')
else:
work_on(x)
multiprocessing模組
multiprocessing
模組所提供的函式與類別能讓你以類似多執行緒的方式編
寫程式碼,只不過現在工作是分散在多個行程(processes)中,而非多個
執行緒:類別
Process
(類似於
threading.Thread
),以及作為同步基本功能 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.