多程序、多執行緒
阿新 • • 發佈:2021-07-12
1.multiprocessing是Python中多程序的模組,使用它能實現多執行緒程式碼編寫
2.啟動子執行緒並結束子執行緒
先定義一個建立執行緒的方法,再在主方法中呼叫Process()函式建立子執行緒
以及父執行緒,再呼叫start()方法以及join()函式實現程序的啟動
def run_proc(name): print('Run child process %s(%s)' %(name,os.getpid())) if __name__ =='__main__': print('Parent process %s.' %os.getpid()) p = Process(target = run_proc,args = ('test',)) print('Child process will start.') p.start() p.join() print('Child process end.')
3.建立執行緒池,先建立定義子執行緒的方法,再在主方法中通過Pool函式配合自己電腦的CPU處理器個數,
再利用Pool函式的例項apply.async方法建立執行緒池
from multiprocessing import Pool import os,time,random #random為隨機函式 #該方法用於子執行緒內容的實現 def long_time_task(name): print('Run task %s(%s)...'% (name,os.getpid())) start = time.time() time.sleep(random.random()*3) end = time.time() #顯示開始和結束時間 print('Task %s runs %0.2f seconds' %(name,(start-end))) if __name__ == '__main__': print('Parent process %s.' %os.getpid()) p = Pool(8) #表示執行緒量 for i in range(9):#這個函式類似於建立執行緒池 p.apply_async(long_time_task,args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('ALL subprocesses done.')
4.執行緒間的通訊通過Queue、Pipes方法來實現
先建立寫方法,像裡面傳入資料,通過put方法傳入,再定義讀方法,從Queue中讀取資料通過get方法
再通過Process方法建立兩個讀寫變數,呼叫start方法和join方法最後呼叫terminate方法終止死迴圈
from multiprocessing import Process,Queue import os,time,random #寫資料程序執行的程式碼: def write(q): print('Process to write :%s'% os.getpid()) for value in ['A','B','C']: print('put %s to queue' %value) q.put(value) time.sleep(random.random()) #讀資料執行的程式碼 def read(q): print('Process to read:%s' % os.getpid()) 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.start() #等待pw結束: pw.join() #pr程序是死迴圈,無法等待其結束,只能強行終止: pr.terminate()
5.啟動執行緒就是把一個函式傳入並建立一個例項,我們通過threading模組中的threading.Thread方法來建立執行緒例項
threading。current_thread().name方法獲得當前執行緒
def loop():#定義方法來建立一個執行緒通過迴圈獲得資訊 print('thread %s is running...'% threading.current_thread().name) n = 0 while n<5 n = n+1 print('thread %s >>>%s'%(threading.current_thread.name,n)) time.sleep(1)#通過time.sleep()函式休眠一會兒輸出 print('threading %s ended.' %threading.current_thread().name) print('thread %s is running...'% threading.current_thread().name) # 通過threading Thread()函式傳入建立執行緒方法名以及執行緒名建立例項執行緒 t = threading.Thread(target = loop,name = 'LoopThread') t.start() t.join() print('thread %s ended.'%threading.current_thread().name)
6.由於執行緒之間的執行是交替的,所以需要通過Lock來規範執行緒的執行
先要宣告一個鎖變數,再獲取鎖,最後通過try-finally語句釋放鎖,再呼叫鎖例項來啟動執行緒和關閉執行緒
7.多核CPU
在Python中任意執行緒在執行前,都會先獲得一個GIL鎖,沒執行100行程式碼,就會釋放資源,讓其他的執行緒執行