Thread synchronization: Mechanism to ensures that two or more concurrent threads do not simultaneously execute some particular program segment known as critical section
Critical section refers to the parts of the program where the shared resource is accessed.
Issues in Synchronization
Race Condition: Occurring of a condition when two or more threads can access shared data and then try to change its value at the same time. Due to this, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes.
Python Code: Without Synchronization
import threading
x = 0
def increment_global():
global x
x += 1
def taskofThread():
for _ in range(50000):
increment_global()
def main():
global x
x = 0
t1 = threading.Thread(target= taskofThread)
t2 = threading.Thread(target= taskofThread)
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))
OUTPUT
x = 100000 after Iteration 0
x = 63883 after Iteration 1
x = 82552 after Iteration 2
x = 100000 after Iteration 3
x = 68994 after Iteration 4
Python Code: Locking Mechanism and Synchronization
import threading
x = 0
def increment():
global x
x += 1
def thread_task(lock):
for _ in range(100000):
lock.acquire()
increment()
lock.release()
def main_task():
global x
x = 0
lock = threading.Lock()
t1 = threading.Thread(target=thread_task, args=(lock,))
t2 = threading.Thread(target=thread_task, args=(lock,))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
OUTPUT
Iteration 0: x = 200000
Iteration 1: x = 200000
Iteration 2: x = 200000
Iteration 3: x = 200000
Iteration 4: x = 200000
Iteration 5: x = 200000
Iteration 6: x = 200000
Iteration 7: x = 200000
Iteration 8: x = 200000
Iteration 9: x = 200000
No comments:
Post a Comment