简体   繁体   English

为什么python线程一旦完成就不能再次运行?

[英]Why can't python threads run again once they have finished?

Assume the following simplest threading example 假定以下最简单的线程示例

from threading import Thread
from time import sleep

def main():
    t = Thread(target=foo)
    t.daemon = True
    t.start()
    sleep(100)
    t.start()

def foo():
    print "foo!"

main()

This attempts to run t twice. 这将尝试运行两次t
The first time succeeds, but the second one throws an exception stating "threads can only run once" 第一次成功,但是第二次抛出异常,指出“线程只能运行一次”

This behavior makes no sense to me. 这种行为对我来说毫无意义。 I would expect a finished thread to be ready to start again. 我希望完成的线程可以重新开始。

My question is WHY threads are not allowed to start again once they have finished? 我的问题是, 为什么线程一旦结束就不允许再次启动?


This question got a "not clear what you're asking" vote - Please tell me what to explain better 这个问题获得了“不清楚您要问的是什么”的投票-请告诉我如何更好地解释

This question got an "opinion based" vote. 这个问题得到了“基于意见”的投票。 This is NOT opinion based. 这不是基于观点的。 I am asking you to explain design decisions of python. 我要你解释python的设计决策。 I hope they didn't go by gut feeling. 我希望他们不要直觉。 I'm pretty sure they didn't. 我很确定他们没有。

The deeper reason why you can't run the same thread more than one time is the same as the reason why you can't go on the same trip more than once. 您不能多次运行同一线程的更深层原因与您不能多次执行同一行的原因相同。 Even if you stay in all of the same places, and do all of the same things when you go back a second time, it's still a different trip. 即使您住在所有相同的地方,并且当您第二次回去时都做同样的事情,那仍然是另一回事。

A thread (a real thread , not the Thread object that gives you the ability to start and manage the thread) is an execution of your code (ie, a "trip" through your code). 线程(真正的线程 ,而不是使您能够启动和管理线程的Thread对象)是代码的执行(即,遍历代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM