Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

multithreading - Start() vs run() for threads in Python?

I'm a little bit confused.

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

while True:
  my_thread.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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

  • 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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...