Python中的线程的Start()vs run()?

cjm*_*671 13 python multithreading

我有点困惑.

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

while True:
  my_thread.start()
Run Code Online (Sandbox Code Playgroud)

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

NPE*_*NPE 9

你是正确的,因为run()它不会产生一个单独的线程.它在当前线程的上下文中运行线程函数.

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

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

最后,将参数传递给一个线程,传球argskwargsThread构造函数.


jor*_*nkg 7

生成线程

不能像这样产生多个线程:

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

改用:

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.
Run Code Online (Sandbox Code Playgroud)


deb*_*bug 6

请阅读线程代码和文档。每个线程对象最多必须调用start()一次。它安排在单独的控制线程中调用对象的run()方法。run()将在上下文中由start()调用,如下所示:

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

    def _bootstrap(self):
        ....
        self._bootstrap_inner()
        ....

    def _bootstrap_inner(self):
        ...
        self.run()
        ...
Run Code Online (Sandbox Code Playgroud)

让我们来演示 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()
Run Code Online (Sandbox Code Playgroud)
$ python3 threading.Thread.py
called by threading.Thread.start()
Run Code Online (Sandbox Code Playgroud)