python 3中的thread.start_new_thread发生了什么

lem*_*ant 21 python multithreading python-multithreading python-3.x

我喜欢将函数转换为线程而没有不必要的行来定义类的能力.我知道_thread,但看起来你不应该使用_thread.对于python 3,是否有一个类似于thread.start_new_thread的良好实践?

Amb*_*ber 33

threading.Thread(target=some_callable_function).start()
Run Code Online (Sandbox Code Playgroud)

或者如果你想通过论证,

threading.Thread(target=some_callable_function,
        args=(tuple, of, args),
        kwargs={'dict': 'of', 'keyword': 'args'},
    ).start()
Run Code Online (Sandbox Code Playgroud)

  • 确保你传递`(firstarg,)`not`(firstarg)` - 记住单元素元组需要将尾随逗号解释为元组. (6认同)

小智 5

不幸的是,这并没有直接的等效项,因为Python 3比Python 2具有更高的可移植性,并且_thread为此目的,该接口被视为过于底层。

在Python 3中,通常最好使用threading.Thread(target=f...)。这使用了不同的语义,但是是首选方法,因为该接口更易于移植到其他Python实现。