1

I wrote the following code while trying to learn threading in python.

    import threading
    import time

    def printWorker(x,y):
        t = time.time()
        while time.time() - t < 10:
            print "Name:%s  Time:%s" %(y,str(time.time() - t))
            time.sleep(x)

    t1 = threading.Thread(target = printWorker(2,'Thread-1'))
    t2 = threading.Thread(target = printWorker(3,'Thread-2'))

    t1.start()
    t2.start()

Im trying to get an output where both Thread-1 and Thread-2 start at same time. IE Print

Thread-1 Stuff, Thread-2 Stuff, Thread-1 Stuff, Thread-2 Stuff, instead of

Thread-1 Stuff, Thread-1 Stuff, Thread-1 Stuff, Thread-1 Stuff, Thread-2 Stuff, Thread-2 Stuff, Thread-2 Stuff, Thread-2 Stuff

Instead Thread-2 Only starts after Thread-1. I've checked online examples but I don't understand what I'm doing wrong mechanically.

1 Answer 1

4

To pass arguments you need to do this:

t1 = threading.Thread(target=printWorker, args=(2, 'Thread-1'))
t2 = threading.Thread(target=printWorker, args=(3, 'Thread-2'))

Your code is invoking printWorker on the main thread and starting two threads with target=None (the return value of printWorker).

Sign up to request clarification or add additional context in comments.

4 Comments

Wow thanks a lot for that help. Also could you point me in a direction where i can understand args and kwargs. Thank you very much. :)
Even after fixing this you might not necessarily observe "Thread-1 Stuff, Thread-2 Stuff, Thread-1 Stuff, Thread-2 Stuff" since you are not doing anything to guarantee the enforcement of that particular schedule. Sleeps are not a reliable mechanism for enforcing required thread scheduling.
I know sleeps arent reliable. This was just a test to see if they are running asynchronously or synchronously.
Ok. Another recommended practice: parent threads should call join on the threads they have started :)

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.