1 Thread Based Parallelism - Thread Synchronization With Lock 2 3 import threading 4 5 shared_resource_with_lock = 0 6 shared_resource_with_no_lock = 0 7 COUNT = 100000 8 shared_resource_lock = threading.Lock() 9 10 11 ####LOCK MANAGEMENT## 12 def increment_with_lock(): 13 global shared_resource_with_lock 14 for i in range(COUNT): 15 shared_resource_lock.acquire() 16 shared_resource_with_lock += 1 17 shared_resource_lock.release() 18 19 20 def decrement_with_lock(): 21 global shared_resource_with_lock 22 for i in range(COUNT): 23 shared_resource_lock.acquire() 24 shared_resource_with_lock -= 1 25 shared_resource_lock.release() 26 27 28 ####NO LOCK MANAGEMENT ## 29 def increment_without_lock(): 30 global shared_resource_with_no_lock 31 for i in range(COUNT): 32 shared_resource_with_no_lock += 1 33 34 35 def decrement_without_lock(): 36 global shared_resource_with_no_lock 37 for i in range(COUNT): 38 shared_resource_with_no_lock -= 1 39 40 41 ####the Main program 42 if __name__ == "__main__": 43 t1 = threading.Thread(target=increment_with_lock) 44 t2 = threading.Thread(target=decrement_with_lock) 45 t3 = threading.Thread(target=increment_without_lock) 46 t4 = threading.Thread(target=decrement_without_lock) 47 t1.start() 48 t2.start() 49 t3.start() 50 t4.start() 51 t1.join() 52 t2.join() 53 t3.join() 54 t4.join() 55 print("the value of shared variable with lock management is %s" 56 % shared_resource_with_lock) 57 print("the value of shared variable with race condition is %s" 58 % shared_resource_with_no_lock) 59 60 Output, 61 the value of shared variable with lock management is 0
# 会发现 shared_resource_with_lock 恒定为 0;
# 因为 lock 的存在, increment 的数值等于 decrement 的数值.
62 the value of shared variable with race condition is -9657
# shared_resource_with_no_lock 会为一个随机, 有时候也为 0.