【一】未加锁会产生的问题
- 所有子线程都会进行阻塞操作,导致最后的改变只是改了一次
from threading import Thread
import time
money = 100
def task():
global money
# 模拟获取到车票信息
temp = money
# 模拟网络延迟
time.sleep(2)
# 模拟购票
money = temp - 1
def main():
task_list = [Thread(target=work) for i in range(100)]
[task.start() for task in task_list]
[task.join() for task in task_list]
# 所有子线程结束后打印 money
print(money)
if __name__ == '__main__':
main()
# 99
【二】加锁后
- 在数据发生变化的地方进行加锁处理
from threading import Thread, Lock
import time
money = 100
# 生成锁
mutex = Lock()
def work():
global money
# 数据发生改变之前加锁
mutex.acquire()
# 模拟获取到车票信息
temp = money
# 模拟网络延迟
time.sleep(0.6)
# 模拟购票
money = temp - 1
# 数据发生改变后解锁
mutex.release()
def main():
task_list = [Thread(target=work) for i in range(100)]
[task.start() for task in task_list]
[task.join() for task in task_list]
# 所有子线程结束后打印 money
print(money)
if __name__ == '__main__':
main()
# 0
标签:__,task,money,list,互斥,线程,main
From: https://www.cnblogs.com/ligo6/p/18218361