Python 併發 multiprocessing-Process
阿新 • • 發佈:2018-12-14
*multiprocessing
支援子程序、通訊和共享資料、執行不同形式的同步。
*Process
建立程序的類:Process([group [, target [, name [, args [, kwargs]]]]]),target表示呼叫物件,args表示呼叫物件的位置引數元組。kwargs表示呼叫物件的字典。Name為別名。Group實質上不使用。
方法有:is_alive()、.join([timeout])、run()、start()、terminate()。屬性有:authkey、daemon(要通過start()設定)、exitcode(程序在執行時為None、如果為–N,表示被訊號N結束)、name、pid。
Process類中,注意daemon是父程序終止後自動終止,且自己不能產生新程序,必須在start()之前設定。
建立函式並將其作為單個程序。
01 |
#!/usr/bin/python |
02 |
03 |
import multiprocessing |
04 |
import time |
05 |
06 |
def clock(interval): |
07 |
while True : |
08 |
print ( "The time is {0}" . format (time.ctime())) |
09 |
time.sleep(interval) |
10 |
11 |
if __name__ = = '__main__' : |
12 |
p = multiprocessing.Process(target = clock, args = ( 15 ,)) |
13 |
p.start() |
將程序定義為類:
01 |
#!/usr/bin/python |
02 |
03 |
import multiprocessing |
04 |
import time |
05 |
06 |
class ClockProcess(multiprocessing.Process): |
07 |
def __init__( self ,interval): |
08 |
multiprocessing.Process.__init__( self ) |
09 |
self .interval = interval |
10 |
11 |
def run( self ): |
12 |
while True : |
13 |
print ( "The time is {0}" . format (time.ctime())) |
14 |
time.sleep( self .interval) |
15 |
16 |
if __name__ = = "__main__" : |
17 |
p = ClockProcess( 15 ) |
18 |
p.start() |
執行結果:
01 |
[email protected]:~/work/python/fork$ python using_multiprocessing.py |
02 |
The time is Fri Apr 22 12:03:04 2011 |
03 |
The time is Fri Apr 22 12:03:19 2011 |
04 |
The time is Fri Apr 22 12:03:34 2011 |
05 |
The time is Fri Apr 22 12:03:49 2011 |
06 |
The time is Fri Apr 22 12:04:04 2011 |
07 |
The time is Fri Apr 22 12:04:19 2011 |
08 |
The time is Fri Apr 22 12:04:34 2011 |
09 |
The time is Fri Apr 22 12:04:49 2011 |
10 |
................. |
為了相容windows而這樣建立類,而且還要注意,在windows下,要在命令列才能執行,用IDE是不行的。
原文:http://www.erlangsir.com/2011/04/22/python-%E5%B9%B6%E5%8F%91-multiprocessing-process/