python 64式: 第13式、執行緒
阿新 • • 發佈:2018-11-08
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import threading ''' 關鍵: 1 併發和並行 併發:交替處理多個任務的能力; 關鍵在併發交替 並行:同時處理多個任務的能力; 關鍵在並行同時 2 多程序與多執行緒 多程序可以充分使用多個cpu 多執行緒不能充分使用多個cpu,原因是全域性直譯器鎖保證同一時刻只能有一個執行緒可以執行程式碼。 本質: 每個執行緒執行時,都需要先獲取全域性直譯器鎖 解決方法: 使用多程序完成多工的處理 3 GIL鎖與互斥鎖 GIL鎖:同一時刻只有一個執行緒使用cpu 互斥鎖:多執行緒對共享資料的有序修改 4 threading.Thread(target=None, args=(), kwargs={}) 使用執行緒的方式: 方式1: 將要執行的方法放入執行緒中 the = threading.Thread(target=myrun, args=(), kwargs{}) the.start() the.join() # 等待執行緒完成才退出 方式2: 繼承執行緒類,重寫run方法 class MyThread(threading.Thread): def run(self): pass 5 執行緒鎖 mutex = threding.Lock() if mutex.acquire(): pass mutex.release() 參考: https://blog.csdn.net/liangkaiping0525/article/details/79490323 https://blog.csdn.net/weixin_41594007/article/details/79485847 ''' G_MUTEX = threading.Lock() G_NUM = 0 def myrun(sleepTime): time.sleep(sleepTime) global G_NUM if G_MUTEX.acquire(): G_NUM += 1 G_MUTEX.release() def useMutex(): threadList = [] for i in range(3): the = threading.Thread(target=myrun, args=(0.1,)) the.start() threadList.append(the) # 等待所有執行緒完成 for the in threadList: the.join() assert G_NUM == 3 def process(): useMutex() if __name__ == "__main__": process()