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