About threading.Thread

Chris Angelico rosuav at gmail.com
Sat Apr 5 01:22:26 EDT 2014


On Sat, Apr 5, 2014 at 4:02 PM, 张佩佩 <zhangpeipei812 at outlook.com> wrote:
> def fun():
>         a = threading.Thread(target=hello(), name='hello')

> It seems that threading.Thread() in file1 not create a new thread but use MainThread.
> Anyone can explain this ?
> Thank you in advance.

Suggestion: Cut the code down until you find the exact bit that's
showing a problem. You don't need two files for this; in fact, all you
need is your definition of hello, the call to threading.Thread(), and
a print statement after it, which you'll see doesn't happen.

The problem here is that you're already *calling* hello() in the
argument list. Before threading.Thread() gets called, its arguments
get fully evaluated... which calls hello(), which infinitely loops.
That's why it's getting called on the main thread.

To spin off a thread that will call hello(), take the parentheses off:

a = threading.Thread(target=hello, name='hello')

That'll pass a function, rather than the return value of that
function, and then Thread can call that.

ChrisA



More information about the Python-list mailing list