首页 > 编程语言 > 详细

python with 线程锁

时间:2019-10-06 19:01:21      阅读:78      评论:0      收藏:0      [点我收藏+]
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

 

python with 线程锁

原文:https://www.cnblogs.com/weilaibuxiangshuo/p/11627840.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!