首页 > 编程语言 > 详细

Python多线程互斥锁使用

时间:2019-11-05 17:40:05      阅读:92      评论:0      收藏:0      [点我收藏+]

# 代码

# coding=utf-8
"""通过使用互斥锁,锁定全局变量,防止数据异常"""
import threading
num = 0
# 创建互斥锁
lock = threading.Lock()


def testOne():
global num
for i in range(100000):
# 在num加1前进行资源抢占,如果抢到则锁定资源,在num+1完成之后进行资源释放
lock.acquire() # 上锁
num += 1
lock.release()# 释放锁
print("testOne 执行完毕,num的值为:",num)


def testTwo():
global num
for i in range(100000):
lock.acquire()
num += 1
lock.release()
print("testTwo 执行完毕,num的值为:",num)


if __name__ == ‘__main__‘:
# 创建线程
t1 = threading.Thread(target=testOne)
t2 = threading.Thread(target=testTwo)
# 启动线程
t1.start()
t1.join()
t2.start()
t2.join()

Python多线程互斥锁使用

原文:https://www.cnblogs.com/walxt/p/11799152.html

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