import threadingimport time # 定义一个全局变量g_num = 0 def test1(num): global g_num for i in range(num): g_num += 1 print(‘-------in test1 g_num={}‘.format(g_num)) def test2(num): global g_num for i in range(num): g_num += 1 print(‘-------in test1 g_num={}‘.format(g_num)) def main(): t1 = threading.Thread(target=test1, args=(1000000,)) # 测试用一万输出的结果是正确的,但是用一百万就有问题了 t2 = threading.Thread(target=test1, args=(1000000,)) t1.start() t2.start() # 等待上面两个进程执行的时间 time.sleep(5) print(‘-------in main Thread g_num={}‘.format(g_num)) if __name__ == ‘__main__‘: main() #上面这个程序会造成资源竞争的问题,最后输出的结果为(结果每次会不同,但是一定不是我们的逻辑结果)
-------in test1 g_num=1172278
-------in test1 g_num=1288801
-------in main Thread g_num=1288801
##解决方案如下(红色字体为新添加的代码)
import threadingimport time # 定义一个全局变量g_num = 0 def test1(num): global g_num for i in range(num): # 上锁如果之前没有被锁上, 那么此时 上锁成功 # 如果上锁之前 已经被上锁了,那么就会堵塞在这里,直到这个锁被解开 mutex.acquire() g_num += 1 mutex.release() print(‘-------in test1 g_num={}‘.format(g_num)) def test2(num): global g_num for i in range(num): mutex.acquire() g_num += 1 mutex.release() print(‘-------in test1 g_num={}‘.format(g_num)) # 创建一个互斥锁,默认是没有上锁的mutex = threading.Lock() def main(): t1 = threading.Thread(target=test1, args=(1000000,)) # 测试用一万输出的结果是正确的,但是用一百万就有问题了 t2 = threading.Thread(target=test1, args=(1000000,)) t1.start() t2.start() # 等待上面两个进程执行的时间 time.sleep(5) print(‘-------in main Thread g_num={}‘.format(g_num)) if __name__ == ‘__main__‘: main()
原文地址:https://www.cnblogs.com/fuyouqiang/p/11770443.html
时间: 2024-11-06 03:32:21