python with 线程锁
阅读原文时间:2023年07月08日阅读:1

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