I want to add n natural numbers but divide it into different threads. I have implemented it. However, I am having a problem getting the sum in the end. Kindly help using synchronization, use a global variable and locking mechanism.
I have used threads. Lets suppose I want to add 30 natural numbers, and divide into three threads, each thread summing up 10 natural numbers, the answer I get is the sum of each thread, I want to get the sum of 30.
I am using Python 2.7
My code :
import threading
a=input("Enter first number")
b=input("Enter second number")
sum=0
def add_func(a,b):
result=0
for i in range(a, b+1):
result =result + i
print result
if __name__ == "__main__":
t1 = threading.Thread(target=add_func(1, 10))
t2 = threading.Thread(target=add_func(11, 20))
t3 = threading.Thread(target=add_func(21, 30))
t1.start()
t2.start()
t3.start()
OUTPUT :
Enter first number1
Enter second number30
55
155
255