Thread Based Parallelism - Thread Synchronization With Lock

时间:2023-03-09 15:29:33
Thread Based Parallelism - Thread Synchronization With Lock
 Thread Based Parallelism - Thread Synchronization With Lock

import threading shared_resource_with_lock = 0
shared_resource_with_no_lock = 0
COUNT = 100000
shared_resource_lock = threading.Lock() ####LOCK MANAGEMENT##
def increment_with_lock():
global shared_resource_with_lock
for i in range(COUNT):
shared_resource_lock.acquire()
shared_resource_with_lock += 1
shared_resource_lock.release() def decrement_with_lock():
global shared_resource_with_lock
for i in range(COUNT):
shared_resource_lock.acquire()
shared_resource_with_lock -= 1
shared_resource_lock.release() ####NO LOCK MANAGEMENT ##
def increment_without_lock():
global shared_resource_with_no_lock
for i in range(COUNT):
shared_resource_with_no_lock += 1 def decrement_without_lock():
global shared_resource_with_no_lock
for i in range(COUNT):
shared_resource_with_no_lock -= 1 ####the Main program
if __name__ == "__main__":
t1 = threading.Thread(target=increment_with_lock)
t2 = threading.Thread(target=decrement_with_lock)
t3 = threading.Thread(target=increment_without_lock)
t4 = threading.Thread(target=decrement_without_lock)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print("the value of shared variable with lock management is %s" \
% shared_resource_with_lock)
print("the value of shared variable with race condition is %s" \
% shared_resource_with_no_lock) Output,
the value of shared variable with lock management is 0
        # 会发现 shared_resource_with_lock 恒定为 0;
        # 因为 lock 的存在, increment 的数值等于 decrement 的数值.
      the value of shared variable with race condition is -9657
        # shared_resource_with_no_lock 会为一个随机, 有时候也为 0.