Python 中的程序同步和池化
程序之間的同步
Multiprocessing 是一個支援使用 API 生成程序的包。此包用於本地和遠端併發。使用此模組,程式設計師可以在給定機器上使用多個處理器。它執行在 Windows 和 UNIX 作業系統上。
此包中提供了所有等效的同步原語。
示例程式碼
from multiprocessing import Process, Lock
def my_function(x, y):
x.acquire()
print ('hello world', y)
x.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target= my_function, args=(lock, num)).start()這裡一個例項可以鎖定以確保一次只有一個程序可以顯示標準輸出。
池化
對於池化,我們使用 Pool 類。當一個人可以建立一個程序池來承載提交給它的所有任務時。
class multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])
池物件控制一個工作程式池,以選擇可以提交哪些作業,並且它支援具有超時、回撥和並行對映實現的非同步結果。
如果程序為 None,則使用 cpu_count(),如果初始化程式不為 None,則此函式呼叫 initializer(*initargs)。
apply(func[, args[, kwds]])
這與 apply() 內建函式相同。它會阻塞直到結果準備就緒,如果它希望並行執行,則 apply_async() 方法更好。
apply_async(func[, args[, kwds[, callback]]])
返回結果物件。
map(func, iterable [, chunksize])
map() 是一個內建函式,它只支援一個可迭代引數。它會阻塞直到結果準備就緒。
在此方法中,可迭代物件被分成多個小塊,這些小塊作為單獨的任務提交到程序池。
map_async(func, iterable[, chunksize[, callback]])
返回結果物件。
imap(func, iterable[, chunksize])
它與 itertools.imap() 相同。
引數的大小與 map() 中使用的大小相同。
imap_unordered(func, iterable[, chunksize])
這與 imap() 相同,只是返回的迭代器不必按順序排列。
close()
當工作程式完成所有任務後,工作程式退出程序。
terminate()
如果我們希望立即停止工作程式程序而不完成任務,則使用此方法。
join()
在使用 join() 方法之前,我們必須使用 close() 和 terminate() 函式。
class multiprocessing.pool.AsyncResult
由 Pool.apply_async() 和 Pool.map_async() 返回。
get([timeout])
此函式在結果到達時返回結果。
wait([timeout])
使用此 wait 函式,我們等待結果可用或直到超時秒過去。
ready()
此函式返回呼叫是否已完成。
successful()
此函式在呼叫在沒有任何錯誤的情況下完成時返回。
示例程式碼
# -*- coding: utf-8 -*- """ Created on Sun Sep 30 12:17:58 2018 @author: Tutorials Point """ from multiprocessing import Pool import time def myfunction(m): return m*m if __name__ == '__main__': my_pool = Pool(processes=4) # start 4 worker processes result = my_pool.apply_async(myfunction, (10,)) # evaluate "f(10)" asynchronously in a single process print (result.get(timeout=1)) print (my_pool.map(myfunction, range(10))) # prints "[0, 1, 4,..., 81]" my_it = my_pool.imap(myfunction, range(10)) print (my_it.next() ) # prints "0" print (my_it.next() ) # prints "1" print (my_it.next(timeout=1) ) # prints "4" unless your computer is *very* slow result = my_pool.apply_async(time.sleep, (10,)) print (result.get(timeout=1) ) # raises multiprocessing.TimeoutError
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP