线程同步能够保证多个线程安全访问竞争资源,最简单的同步机制是引入互斥锁
1 from threading import Thread,Lock 2 3 g_num = 0 4 5 def test1(): 6 global g_num 7 #上锁 8 mutex.acquire() 9 for i in range(100000): 10 g_num +=1 11 #解锁 12 mutex.release() 13 14 print("test1----g_num= %d"%g_num) 15 16 def test2(): 17 global g_num 18 #上锁 19 mutex.acquire() 20 for i in range(100000): 21 g_num += 1 22 #解锁 23 mutex.release() 24 print("test2----g_num = %d"%g_num) 25 26 27 # 创建互斥锁 28 mutex = Lock() 29 p1 = Thread(target = test1) 30 p1.start() 31 32 p2 = Thread(target = test2) 33 p2.start() 34 35 p1.join() 36 p2.join() 37 38 print("---g_num---%d"%g_num)
执行结果
test1----g_num= 100000
test2----g_num = 200000
---g_num---200000