The provided code is about 2 thread
trying to access the function increment()
to increment the value of a global variable
x. I have designed a semaphore class
for process synchronization. So the expected increment of each thread is expected to be 1000000
summing up to 2000000
. But actual output is not reaching up to 2000000
. The output is reaching up to 1800000 - 1950000
. Why are all loop not executing?
import threading as th
x=0
class Semaphore:
def __init__(self):
self.__s = 1
def wait(self):
while(self.__s==0):
pass
self.__s-=1
def signal(self):
self.__s+=1
def increment(s):
global x
s.wait()
x+=1
s.signal()
def task1(s):
for _ in range(1000000):
increment(s)
def task2(s):
for _ in range(1000000):
increment(s)
def main():
s = Semaphore()
t1 = th.Thread(target=task1,name="t1",args=(s,))
t2 = th.Thread(target=task2,name="t1",args=(s,))
t1.start()
t2.start()
#Checking Synchronization
for _ in range(10):
print("Value of X: %d"%x)
#waiting for termination of thread
t2.join()
t1.join()
if __name__=="__main__":
main()
print("X = %d"%x) #Final Output
Output:
Value of X: 5939
Value of X: 14150
Value of X: 25036
Value of X: 50490
Value of X: 54136
Value of X: 57674
Value of X: 69994
Value of X: 84912
Value of X: 94284
Value of X: 105895
X = 1801436