0

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()
0

1 Answer 1

1

The problem here is that you have the target as a() rather than a (note the parentheses). What that means is, you are calling the function a and then passing the result of that as the target to Thread. That isn't what you wanted - you want the target to be the function a itself. So just remove the parentheses when instantiating your Threads like so:

if __name__=="__main__":
    t1=Thread(target=a)
    t2=Thread(target=b)
    t1.start()
    t2.start()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.