Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
multiprocessing 模組
|
457
Queue
提供了慣用語「尋求原諒比取得許可容易(It
s easier to ask
forgiveness than permissionEAFP)」(涵蓋於前面的「錯誤檢查策略」)
的一個良好實例。由於多執行緒,
q
的每個非變動方法(
empty
full
qsize
)都只能是諮詢式的。當其他的某個執行緒開始執行,並變動了
q
那麼在一個執行緒從非變動方法取得資訊的那個時刻到該執行緒依據那個
資訊採取行動的時刻之間,事情可能發生了變化。因此仰賴「跳躍前先看
情況(look before you leapLBYL)」慣用語是沒用的,而試著用鎖修補
事情則是大大地白費力氣。單純避免脆弱的 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.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819