【问题标题】:Start() vs run() for threads in Python?Python中的线程的Start()与run()?
【发布时间】:2014-04-22 16:11:16
【问题描述】:

我有点困惑。

我正在尝试在循环中启动一个线程,即:

while True:
  my_thread.start()

我有点困惑,因为我已经让它与my_thread.run() 一起工作,但是当我将它换成 start() 时,它无法启动多个线程。我的 .run() 实际上不是一个单独的线程,如果不是,我应该做什么 ?最后,我可以将变量传递给 start() 吗?

【问题讨论】:

  • 您是否阅读过这些方法的文档?
  • 是的,但我很难找到合适的例子来解释这些概念。
  • docs.python.org/2.7/library/threading.html#module-threading start(): Start the thread’s activity. [...] run() method (is) invoked in a separate thread of control. VS run(): Method representing the thread’s activity.
  • 这很有帮助,谢谢。

标签: python multithreading


【解决方案1】:

您是正确的,run() 不会产生单独的线程。它在当前线程的上下文中运行线程函数

我不清楚你想通过循环调用start() 来实现什么。

  • 如果您希望线程重复执行某项操作,请将循环移到线程函数中。
  • 如果您需要多个线程,则创建多个 Thread 对象(并在每个对象上调用一次 start())。

最后,要将参数传递给线程,请将argskwargs 传递给Thread constructor

【讨论】:

  • 我想做的是处理实时传入的视频。我希望线程做的是异步处理传入的帧,然后用结果更新一些全局变量。我希望它每帧最多执行一次,但如果每隔几帧执行一次就可以了。帧的获取是一个连续的循环。
【解决方案2】:

衍生线程

您可以像这样生成多个线程:

while True:
   my_thread.start()     # will start one thread, no matter how many times you call it

改用:

while True:
   ThreadClass( threading.Thread ).start() # will create a new thread each iteration
   threading.Thread( target=function, args=( "parameter1", "parameter2" ))

def function( string1, string2 ):
  pass # Just to illustrate the threading factory. You may pass variables here.

【讨论】:

    【解决方案3】:

    请阅读threading code and docsstart() 每个线程对象最多只能调用一次。它安排在单独的控制线程中调用对象的 run() 方法。 run() 将由 start() 在上下文中调用,如下所示:

        def start(self):
            ....
            _start_new_thread(self._bootstrap, ())
            ....
    
        def _bootstrap(self):
            ....
            self._bootstrap_inner()
            ....
    
        def _bootstrap_inner(self):
            ...
            self.run()
            ...
    

    让我们来演示一下 start() 和 run()。

    class MyThread(threading.Thread):
    
        def __init__(self, *args, **kwargs):
            super(MyThread, self).__init__(*args, **kwargs)
    
        def run(self):
            print("called by threading.Thread.start()")
    
    
    if __name__ == '__main__':
        mythread = MyThread()
        mythread.start()
        mythread.join()
    

    $ python3 threading.Thread.py
    called by threading.Thread.start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多