python with 線程鎖


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM