I know this question has been asked multiple times but I couldn't find an answer which would help me. My question is can we execute two functions in parallel in python where each function has a for loop running and printing some values. For example, I have two functions a() and b() where a() is printing the numbers 1..n (say n=3) and b() is printing the numbers 11..n(say n=13) along with the current time. I expect the output to be like :
function a :1 2018-11-02 15:32:58
function b :11 2018-11-02 15:32:58
function a :2 2018-11-02 15:32:59
function b :12 2018-11-02 15:32:59
but it currently prints the following :
function a :1 2018-11-02 15:32:58
function a :2 2018-11-02 15:32:59
function b :11 2018-11-02 15:33:00
function b :12 2018-11-02 15:33:01
Code:
import time
from threading import Thread
import datetime
def a():
for i in range(1,3):
print 'function a :'+str(i) + ' ' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(1)
def b():
for i in range(11,13):
print 'function b :'+str(i) + ' ' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(1)
if __name__=="__main__":
t1=Thread(target=a())
t2=Thread(target=b())
t1.start()
t2.start()