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
570 views
in Technique[技术] by (71.8m points)

multithreading - Meaning of daemon property on Python Threads

I'm a little confused about what setting a thread to be a daemon means.

The documentation says this:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

I'm not sure what makes this different from a normal thread.

Is this saying that this program won't ever finish?

def threadfunc():
    while True:
        time.sleep(1)

threading.Thread(target=threadfunc).start()

Even though the main thread finishes it's execution. While will finish immediately?

def threadfunc():
    while True:
        time.sleep(1)

th = threading.Thread(target=threadfunc)
th.daemon = True
th.start()

I ask because I have a situation where in my main thread I'm calling sys.exit(), and the process just hangs and my other threads are running as I can see the log.

Does this have anything to do with sys.exit() being called with threads alive?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Is this saying that this program won't ever finish?

Yes, that program won't finish, just try it out.

I ask because I have a situation where in my main thread I'm calling sys.exit(), and the process just hangs and my other threads are running as I can see the log. Does this have anything to do with sys.exit() being called with threads alive?

Yes, even exit won't stop other threads, it simply raises SystemExit in the main thread. So while the main thread will stop (just like it does on any other unhandled Exception), all other non-daemonic threads will continue to work.


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

...