Start()vs run()for Python中的线程? [英] Start() vs run() for threads in Python?

查看:68
本文介绍了Start()vs run()for Python中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.

我正在尝试以循环方式启动线程,即:

I'm trying to start a thread in a loop, i.e.:

while True:
  my_thread.start()

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

I'm a little confused because I've had it working with my_thread.run(), but when I swapped it to start() it fails to start more than one thread. Is my .run() not actually a separate thread, and if not what should I be doing? Lastly, can I pass variables into start()?

推荐答案

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

You are correct in that run() does not spawn a separate thread. It runs the thread function in the context of the current thread.

我不清楚您要通过循环调用start()来达到什么目的.

It is not clear to me what you are trying to achieve by calling start() in a loop.

  • 如果您希望线程重复执行某项操作,则将循环移到线程函数中.
  • 如果需要多个线程,则创建多个Thread对象(并在每个对象上调用一次start()).
  • If you want your thread to repeatedly do something, then move the loop into the thread function.
  • If you want multiple threads, then create multiple Thread objects (and call start() once on each of them).

最后,要将参数传递给线程,请将argskwargs传递给 Thread构造函数.

Finally, to pass arguments to a thread, pass args and kwargs to the Thread constructor.

这篇关于Start()vs run()for Python中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆