多進程
linux平臺例子:
Unix/Linux操作系統提供了一個fork()
系統調用,它非常特殊。普通的函數調用,調用一次,返回一次,但是fork()
調用一次,返回兩次,因爲操作系統自動把當前進程(稱爲父進程)複製了一份(稱爲子進程),然後,分別在父進程和子進程內返回。
子進程永遠返回0
,而父進程返回子進程的ID。這樣做的理由是,一個父進程可以fork出很多子進程,所以,父進程要記下每個子進程的ID,而子進程只需要調用getppid()
就可以拿到父進程的ID。
import os,random print 'Process (%s) start...' % os.getpid() p1 = os.fork() if pid==0: #第一次執行返回0的情況 print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()) else: #第一次執行返回子進程ID的情況 print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)
windows例子
from multiprocessing import Process import os # 子進程要執行的代碼 def run_proc(name): print 'Run child process %s (%s)...' % (name, os.getpid()) #創建一個Process實例,用start()方法啓動 #join()方法可以等待子進程結束後再繼續往下運行,通常用於進程間的同步 if __name__=='__main__': print 'Parent process %s.' % os.getpid() p = Process(target=run_proc, args=('test',)) print 'Process will start.' p.start() p.join() print 'Process end.' #執行結果如下: Parent process 928. Process will start. Run child process test (929)... Process end.
多進程使用隊列進行 進程間通信
from multiprocessing import Process, Queue import os, time, random # 寫數據進程執行的代碼: def write(q): for value in ['A', 'B', 'C']: print 'Put %s to queue...' % value q.put(value) time.sleep(random.random()) # 讀數據進程執行的代碼: def read(q): while True: value = q.get(True) print 'Get %s from queue.' % value if __name__=='__main__': # 父進程創建Queue,並傳給各個子進程: q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) # 啓動子進程pw,寫入: pw.start() # 啓動子進程pr,讀取: pr.start() # 等待pw結束: pw.join() # pr進程裏是死循環,無法等待其結束,只能強行終止: pr.terminate() 運行結果如下: Put A to queue... Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue.