【发布时间】:2011-09-13 05:44:35
【问题描述】:
我喜欢将函数转换为线程而无需定义类的不必要行的能力。我知道_thread,但看来您不应该使用_thread。 python 3 是否有等效于 thread.start_new_thread 的良好实践?
【问题讨论】:
标签: python multithreading python-3.x python-multithreading
我喜欢将函数转换为线程而无需定义类的不必要行的能力。我知道_thread,但看来您不应该使用_thread。 python 3 是否有等效于 thread.start_new_thread 的良好实践?
【问题讨论】:
标签: python multithreading python-3.x python-multithreading
threading.Thread(target=some_callable_function).start()
或者如果你想传递参数,
threading.Thread(target=some_callable_function,
args=(tuple, of, args),
kwargs={'dict': 'of', 'keyword': 'args'},
).start()
【讨论】:
(firstarg,) 而不是 (firstarg) - 请记住,单元素元组需要将尾随逗号解释为元组。
callable(**kwargs): 之类的东西,我会得到TypeError: callable() takes 0 positional arguments but 1 was given,如果我使用callable(kwargs):,我会得到TypeError: callable() got an unexpected keyword argument 'raw'。
threading.Thread(target=callable,kwargs=kwargs)
不幸的是,没有直接的等价物,因为 Python 3 旨在比 Python 2 更具可移植性,而 _thread 接口被认为太低级了。
在 Python 3 中,最佳实践通常是使用 threading.Thread(target=f...)。这使用不同的语义,但更受欢迎,因为该接口更容易移植到其他 Python 实现。
【讨论】: