【问题标题】:What happened to thread.start_new_thread in python 3python 3中的thread.start_new_thread发生了什么
【发布时间】:2011-09-13 05:44:35
【问题描述】:

我喜欢将函数转换为线程而无需定义类的不必要行的能力。我知道_thread,但看来您不应该使用_thread。 python 3 是否有等效于 thread.start_new_thread 的良好实践?

【问题讨论】:

    标签: python multithreading python-3.x python-multithreading


    【解决方案1】:
    threading.Thread(target=some_callable_function).start()
    

    或者如果你想传递参数,

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

    【讨论】:

    • 我正在使用方法 2 将一个参数传递给线程,并且收到错误:* 之后的参数必须是序列,而不是它。你知道这意味着什么吗?
    • 确保传递的是 (firstarg,) 而不是 (firstarg) - 请记住,单元素元组需要将尾随逗号解释为元组。
    • 可调用方法签名是什么样的?如果我使用callable(**kwargs): 之类的东西,我会得到TypeError: callable() takes 0 positional arguments but 1 was given,如果我使用callable(kwargs):,我会得到TypeError: callable() got an unexpected keyword argument 'raw'
    • @henrikstroem threading.Thread(target=callable,kwargs=kwargs)
    【解决方案2】:

    不幸的是,没有直接的等价物,因为 Python 3 旨在比 Python 2 更具可移植性,而 _thread 接口被认为太低级了。

    在 Python 3 中,最佳实践通常是使用 threading.Thread(target=f...)。这使用不同的语义,但更受欢迎,因为该接口更容易移植到其他 Python 实现。

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2018-03-03
      • 2020-04-05
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      相关资源
      最近更新 更多