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 total13 global lock14 for i in range(1000000):15 # 获取锁16 lock.acquire()17 total += 118 # 释放锁19 lock.release()20 21 22 def desc():23 global total24 global lock25 for i in range(1000000):26 # 获取锁27 lock.acquire()28 total -= 129 # 释放锁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 += 142 43 44 def desc1(a):45 a -= 146 47 48 """49 1.load a50 2.load 151 3.+(-)52 4.赋值给a53 """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_VALUENone 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_VALUENoneC:\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_VALUENone 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_VALUENone0C:\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_VALUENone 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_VALUENone0
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 total14 global lock15 for i in range(1000000):16 # 获取锁17 lock.acquire()18 lock.acquire()19 total += 120 # 释放锁21 lock.release()22 lock.release()23 24 25 def desc():26 global total27 global lock28 for i in range(1000000):29 # 获取锁30 lock.acquire()31 total -= 132 # 释放锁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总结
以上是内存溢出为你收集整理的【10.4】线程同步--Lock、RLock全部内容,希望文章能够帮你解决【10.4】线程同步--Lock、RLock所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)