简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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