標籤:binary imp data- oba track range art 介面 tail
多進程
在Unix/Linux下,為我們提供了類似c中<unistd.h>標頭檔裡的的fork()函數的介面,這個函數位於os模組中,相同與c中類似,對於父進程fork()調用返回子進程ID,對於子進程返回0
import os, timepid = os.fork()if pid == 0: while True: print ‘child process‘ time.sleep(1)else: while True: print ‘parent process‘ time.sleep(3)
考慮到Windows並沒有這個調用,python為我們提供了跨平台的版本號碼。這就是multiprocessing模組。通過multiprocessing模組中的Process類可實現跨平台的多進程。使用方法很easy
#coding:utf-8from multiprocessing import Processimport os, timedef handler(args):print ‘process parameter is %s‘ % argswhile True:print ‘child process‘time.sleep(1)if __name__==‘__main__‘: print ‘parent process is %d‘ % os.getpid() child_proc = Process(target = handler, args=(‘test parameter‘,)) #指定子進程開始啟動並執行函數 child_proc.start() while True: print ‘parent process‘ time.sleep(3)
注意:若不加if __name__==‘__main__‘。子進程啟動後會將模組內的代碼再運行一遍。為避免不必要的錯誤,應該加上它
Python為了更方便的使用多進程還提供了進程池Pool, 位於multiprocessing模組中,進程池用於對於並發響應要求較高的條件中,預先分配進程,節省了處理過程中fork的開銷
關於很多其它進程池的內容可參考 http://blog.csdn.net/aspnet_lyc/article/details/38946915#t3 中的TCP預先派生子進程server
#coding:utf-8from multiprocessing import Poolimport os, time, randomdef handler(proc_args): print proc_argsif __name__ == ‘__main__‘: pool = Pool(4) #設定進程池中的進程數 for loop in range(4):pool.apply_async(handler, args=(loop,)) #apply_async(func,args),從進程池中取出一個進程運行func,args為func的參數。返回一個 AsyncResult的對象。對該對象調用get()方法能夠獲得結果。 pool.close() #不在往進程池中加入進程 pool.join() #等待全部子進程結束 print ‘All child processes done‘
多線程
Python中對於多線程提供了thread和threading模組, threading對thread進行了封裝,更易用。python官網的描寫敘述例如以下
This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchronization, simple locks (also called mutexes or binary semaphores) are provided. The threading module provides an easier to use and higher-level threading API built on top of this module
調用thread模組中的start_new_thread()函數來產生新線程
import threaddef thread_handler(args): print argsif __name__ == ‘__main__‘: thread.start_new_thread(thread_handler, (‘test parameter‘,)) while True: pass
將線程函數傳入並建立Thread執行個體。然後調用start()建立線程並運行
import threadingdef thread_handler(args): print argsif __name__ == ‘__main__‘: th1 = threading.Thread(target=thread_handler, args=(‘test parameter 1‘,)) th2 = threading.Thread(target=thread_handler, args=(‘test parameter 2‘,)) th1.start() th2.start() th1.join() th2.join() print ‘All threads ended‘
python 並發編程入門