Python:在线程中运行函数不修改current_thread()

9 投票
2 回答
20618 浏览
提问于 2025-04-17 19:23

我现在正在尝试了解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()

我注意到这两个打印输出的内容是一样的。为什么线程没有变化呢?

2 个回答

8

你在调用这个函数的时候,它还没有被传给 Thread 的构造函数。而且,你传的参数也不对(构造函数的第一个位置参数是 group)。假设 func1 返回的是 None,那么你实际上是在做类似于调用 threading.Thread(None) 或者 threading.Thread() 的事情。

关于这个问题,详细的解释可以在 线程文档 中找到。

要让你的代码正常工作,可以试试这个:

t1 = threading.Thread(target=func1, args=(arg1, arg2))
t1.start()
t1.join()
20

你现在是在执行这个函数,而不是把它传递过去。试试这样做:

t1 = threading.Thread(target = func1, args = (arg1, arg2))

撰写回答