Python中的线程:Start()和run()的区别?

32 投票
3 回答
37721 浏览
提问于 2025-04-18 03:46

我有点困惑。

我想在一个循环里启动一个线程,也就是:

while True:
  my_thread.start()

我有点迷糊,因为我之前用 my_thread.run() 是可以工作的,但当我换成 start() 的时候,就无法启动多个线程了。我的 run() 其实不是一个独立的线程吗?如果不是,那我应该怎么做呢?最后,我可以把变量传递给 start() 吗?

3 个回答

7

请查看 线程代码和文档start() 方法每个线程对象最多只能调用一次。这个方法会安排调用对象的 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()
7

创建线程

不能像这样创建多个线程:

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.
23

你说得对,run() 并不会创建一个新的线程。它是在当前线程的上下文中运行线程的功能。

我不太明白你为什么要在循环中调用 start()

  • 如果你想让你的线程重复做某件事,那就把循环放到线程的功能里去。
  • 如果你想要多个线程,那就创建多个 Thread 对象(然后在每个对象上调用一次 start())。

最后,要给线程传递参数,可以把 argskwargs 传给 Thread 构造函数

撰写回答