PhilliPy
PhilliPy

Reputation: 23

Why is the 2nd thread not starting?

This code doesn't give me the output I expect. Something must be wrong, but I cannot understand what it could be.

import thread
import time

def func1(threadName, sleepTime):
    while 1 < 2:
        time.sleep(sleepTime)
        print "%s" % (threadName)

def func2(threadName, sleepTime):
    while 1 < 2:
        time.sleep(sleepTime)
        print "%s" % (threadName)


try:
    thread.start_new_thread(func1("slow" , 5))
    thread.start_new_thread(func2("fast" , 1))
except Exception, e:
    print str(e)

The output I expect is something like:

fast
fast
fast
fast
slow
fast

and so on, but only the 1st thread seems to be starting. I implemented the "try and except" block later to see if there's an error somewhere but no error!

Upvotes: 2

Views: 131

Answers (1)

Brilliand
Brilliand

Reputation: 13714

It looks like the functions are being called before the threads are started. I'm not very familiar with Python, but try:

thread.start_new_thread(func1, ("slow" , 5))
thread.start_new_thread(func2, ("fast" , 1))

Notice the comma after the function name - you pass in the function as one argument, and a tuple of the argument parameters as a separate argument. This lets start_new_thread call your function when the new thread is ready.

Upvotes: 6

Related Questions