9

我目前正在尝试弄清楚线程如何在 python 中工作。

我有以下代码:

def func1(arg1, arg2):

    print current_thread()
    ....

class class1:

    def __init__():
        ....

    def func_call():
        print current_thread()
        t1 = threading.Thread(func1(arg1, arg2))
        t1.start()
        t1.join()

我注意到的是两个打印输出相同的东西。为什么线程没有变化?

4

2 回答 2

20

You're executing the function instead of passing it. Try this instead:

t1 = threading.Thread(target = func1, args = (arg1, arg2))
于 2013-03-17T12:33:40.897 回答
8

You are calling the function before it is given to the Thread constructor. Also, you are giving it as the wrong argument (the first positional argument to the Thread constructor is the group). Assuming func1 returns None what you are doing is equivalent to calling threading.Thread(None) or threading.Thread(). This is explained in more detail in the threading docs.

To make your code work try this:

t1 = threading.Thread(target=func1, args=(arg1, arg2))
t1.start()
t1.join()
于 2013-03-17T12:33:48.370 回答