import threading import time num = 0 # 全局變量多個線程可以讀寫,傳遞數據 mutex = threading.RLock() # 創建一個鎖 class Mythread(threading.Thread): def run(self): global num with mutex: # with RLock的作用相當於自動獲取和釋放鎖(資源) for i in range(1000): # 鎖定期間,其他線程不可以干活 num += 1 print(num) mythread = [] for i in range(5): t = Mythread() t.start() mythread.append(t) for t in mythread: t.join() print("ceshi")
另一種方式,不需傳遞threading.Thread,直接操作屬性:
import threading import time num = 0 # 全局變量多個線程可以讀寫,傳遞數據 class Mythread(): mutex = threading.RLock() # 創建一個類屬性鎖 def run(self): global num with mutex: # with RLock的作用相當於自動獲取和釋放鎖(資源) for i in range(1000): # 鎖定期間,其他線程不可以干活 num += 1 print(num) mythread = [] t=Mythread() t.run() print("ceshi")
根據網絡搜索整合:
參考:https://blog.csdn.net/houyanhua1/article/details/78233519