I have two functions f1
and f2
which increment an integer specific number of times in a loop inside these two functions.
Two ways I call these functions.
1) One by one, that is first f1
then f2
.
2) Create a thread t1
to run function f1
and thread t2
to run function f2
.
As soon in the code below, I have tried both the ways.
from threading import Thread
import time
import datetime
from queue import Queue
def f1(a):
for i in range(1,100000000):
a+=1
return a
def f2(a):
for i in range(1,100000000):
a+=1
return a
if __name__ == '__main__':
que1 = Queue()
que2 = Queue()
# t2 = Thread(target=f1(a),name='t2')
a = 0
s_t = time.time()
print('Value of a, before calling function f1: ',a)
a=f1(a)
print('Value of a, after calling function f1: ',a)
a = 0
print('Value of a, before calling function f2: ',a)
a=f2(a)
print('Value of a, after calling function f2: ',a)
print('Time taken without threads: ',datetime.timedelta(seconds=time.time()-s_t))
s_t = time.time()
a = 0
print('Value of a, before calling function f1 through thread t1: ',a)
t1 = Thread(target=lambda q, arg1: q.put(f1(arg1)), args=(que1,a),name = 't1')
print('Value of a, before calling function f2 through thread t2: ',a)
t2 = Thread(target=lambda q, arg1: q.put(f2(arg1)), args=(que2,a),name = 't2')
t1.start()
t2.start()
t1.join()
print('Value of a, after calling function f1 through thread t1: ',que1.get())
t2.join()
print('Value of a, after calling function f2 through thread t2: ',que2.get())
print('Time taken with threads: ',datetime.timedelta(seconds=time.time()-s_t))
Expected threads to do the jobs faster than calling the functions one after the other but it's not the case here.
Here's the output
Value of a, before calling function f1: 0
Value of a, after calling function f1: 99999999
Value of a, before calling function f2: 0
Value of a, after calling function f2: 99999999
Time taken without threads: 0:00:07.623239
Value of a, before calling function f1 through thread t1: 0
Value of a, before calling function f2 through thread t2: 0
Value of a, after calling function f1 through thread t1: 99999999
Value of a, after calling function f2 through thread t2: 99999999
Time taken with threads: 0:00:27.274876
What is going wrong?