python的多進程編程(2)

  • 繼續翻譯python的multiprocess,開發環境我就不再說了,(1)中有交代,閒話休提,直接上正文

16.6.1.5 Using a pool of workers(使用輔助進程池)

Pool類是輔助進程池。它有一些方法,可以讓任務以多種方式分配給輔助進程。
例如:

from multiprocessing import Pool


def f(x):
    return x * x

if __name__ == '__main__':
    pool = Pool(processes=4)  # 創建4個輔助進程
    result = pool.apply_async(f, [10])  # 異步計算"f(10)"
    print result.get(timeout=1)  # 打印"100",除非你電腦*特別*慢
    print pool.map(f, range(10))  # 打印 "[0, 1, 4,..., 81]"

注意:只有pool創建的進程才能使用pool的方法

注意:這個包裏的功能需要有__main__模塊。在Progarmming guidelines裏有介紹,但是這裏很有必要強調。這意味着,有些例子,就像Pool,在交互性解釋器裏無法工作。例如:

>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
...     return x*x
...
>>> p.map(f, [1,2,3])
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-3:
Traceback (most recent call last):
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'

(如果你試着這樣寫,會隨機輸出3個異常信息,你必須想辦法停止主進程)

16.6.2 參考

multiprocessing包河threading模塊的大部分API是一樣的

16.6.2.1 進程和異常

class multiprocessing.Process(group=None,target=None,name=None,args=(),kwargs={})
Process對象表示他在一個單獨的進程裏運行。Process class有和threading.Thread一樣的方法。
在創建Process時,構造器應該含有關鍵字參數。group應該總是None;它存在的唯一意思是和threading.Thread兼容。target是一個可調用對象,通過run()方法調用。它默認是None,即什麼都不做。name是進程的名字。默認情況下,進程的唯一名稱是這樣的:
Process-N1:N2:…:Nk‘, N1,N2……Nk是整數序列,整數的長度由進程決定。args是target方法的參數元組。kwargs是target的關鍵字參數字典。默認情況下,不傳任何參數給target.
如果子類重寫了process的構造器,在進程中添加任何方法前,必須調用基類構造器(Process.__init__())
run()
表示進程的活動方法
你可以在子類中重寫此方法。 The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
start()
開啓進程的活動方法
每個進程必須至少調用這個方法一次。它在一個單獨的進程中啓用對象的run()方法。
join([timeout])
阻塞主進程,直到開啓了join()方法的進程結束或超時
如果timeout 是None就沒有超時
一個進程可以使用join()方法多次
一個進程不能join它自身,因爲這回造成死鎖(deadlock)。在一個進程start前join是錯誤的。
name
進程的名字
名字是string,只用作唯一標識。它沒有任何意義。多個進程有相同的name,構造器會初始化name。
is_alive()
返回進程是否alive
一般情況下,一個進程對象從start()開始直到子進程結束都是alive的
daemon
進程的守護進程標識,一個布爾值。必須在start()方法前設置。
它的初始值繼承自創建它的進程
當一個進程退出時,它的所有子守護進程會結束
注意:守護進程不能創建子進程。Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited。

除了threading.Thread的API,Process對象還提供了下面的屬性和方法:
pid
return進程的ID.進程產生前,它是None
exitcode
子進程的退出代碼。如果進程還沒有結束,這個值是None.A negative value -N indicates that the child was terminated by signal N.
authkey
進程的身份標識key(字節字符串)
當multiprocessing初始化,主進程會被賦值一個隨機字符串(os.urandom())
當進程對象被創建,它會繼承父進程的身份標識key,雖然這個值可以通過設置authkey來改變
查看Authentication keys.
terminate()
結束進程。Unix使用終止信號。Windows使用TerminateProcess()。 Note that exit handlers and finally clauses, etc., will not be executed。
警告:If this method is used when the associated process is using a pipe or queue then the pipe or queue is liable to become corrupted and may become unusable by other process. Similarly, if the process has acquired a lock or semaphore etc. then terminating it is liable to cause other processes to deadlock.
注意:start(),join(),is_alive(),terminate()和exitcode方法只能由創建進程的對象調用
一些Process的方法的使用的例子:

>>> import multiprocessing, time, signal
>>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
>>> print p, p.is_alive()
<Process(Process-1, initial)> False
>>> p.start()
>>> print p, p.is_alive()
<Process(Process-1, started)> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print p, p.is_alive()
<Process(Process-1, stopped[SIGTERM])> False
>>> p.exitcode == -signal.SIGTERM
True

exception multiporcessing.BufferTooShort
當Connection.recv_bytes_into()方法時,如果提供的buffer對象太小,會拋出這個異常
如果e是BufferTooShort的實例,e.args[0]會提供以byte string形式的信息。

今天就到這裏,如果有錯誤,紕漏和需要改進的地方,請不吝指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章