所有子线程都会进行阻塞操作,导致最后的改变只是改了一次
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,互斥,线程,import,main
From: https://www.cnblogs.com/zenopan101861/p/18208228