1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import dis 5 import threading 6 from threading import Lock 7 total = 0 8 lock = Lock() 9 10 11 def add(): 12 global total 13 global lock 14 for i in range(1000000): 15 # 获取锁 16 lock.acquire() 17 total += 1 18 # 释放锁 19 lock.release() 20 21 22 def desc(): 23 global total 24 global lock 25 for i in range(1000000): 26 # 获取锁 27 lock.acquire() 28 total -= 1 29 # 释放锁 30 lock.release() 31 32 33 thread1 = threading.Thread(target=add) 34 thread2 = threading.Thread(target=desc) 35 36 thread1.start() 37 thread2.start() 38 39 40 def add1(a): 41 a += 1 42 43 44 def desc1(a): 45 a -= 1 46 47 48 """ 49 1.load a 50 2.load 1 51 3.+(-) 52 4.赋值给a 53 """ 54 print(dis.dis(add1)) 55 print(dis.dis(desc1)) 56 57 thread1.join() 58 thread2.join() 59 60 print(total)
41 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (1) 4 INPLACE_ADD 6 STORE_FAST 0 (a) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE None 45 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (1) 4 INPLACE_SUBTRACT 6 STORE_FAST 0 (a) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE None C:\Users\Administrator\Python\imooc>python demo.py 41 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (1) 4 INPLACE_ADD 6 STORE_FAST 0 (a) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE None 45 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (1) 4 INPLACE_SUBTRACT 6 STORE_FAST 0 (a) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE None 0 C:\Users\Administrator\Python\imooc>python demo.py 41 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (1) 4 INPLACE_ADD 6 STORE_FAST 0 (a) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE None 45 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (1) 4 INPLACE_SUBTRACT 6 STORE_FAST 0 (a) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE None 0
1.用锁会影响性能
2.锁会引起死锁
RLock
1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import threading 5 # RLock,在同一个线程里面,可以连续调用多次acquire,一定要注意acquire的次数要和release的次数相等 6 # 线程间还是有相互竞争的关系 7 from threading import RLock 8 total = 0 9 lock = RLock() 10 11 12 def add(): 13 global total 14 global lock 15 for i in range(1000000): 16 # 获取锁 17 lock.acquire() 18 lock.acquire() 19 total += 1 20 # 释放锁 21 lock.release() 22 lock.release() 23 24 25 def desc(): 26 global total 27 global lock 28 for i in range(1000000): 29 # 获取锁 30 lock.acquire() 31 total -= 1 32 # 释放锁 33 lock.release() 34 35 36 thread1 = threading.Thread(target=add) 37 thread2 = threading.Thread(target=desc) 38 39 thread1.start() 40 thread2.start() 41 42 thread1.join() 43 thread2.join() 44 45 print(total)
0
原文地址:https://www.cnblogs.com/zydeboke/p/11298248.html
时间: 2024-10-12 20:26:06