prt
prt

Reputation: 215

Daemon thread vs Non Daemon thread in python

I have following code :

import threading 
from time import sleep

def print_function1():
    while True:
        print("Hi this is function 1\n") 
        sleep(2)

if __name__ == "__main__": 
    # creating thread 
    t1 = threading.Thread(target=print_function1 ) 

    t1.daemon = True

    # starting thread 1 
    t1.start() 

    sleep(10)

    # both threads completely executed 
    print("Done!") 

Now I am not able in understand what difference does it make if I set , t1.daemon True or False , I am running code in spider Ipython console.

In both cases program don't seems to exit, It keep printing "Hi this is function 1". My assumption was daemon thread will keep running when main thread finishes , but normal thread will exit.

can anyone explain please.

Upvotes: 2

Views: 3202

Answers (2)

Amit Sharma
Amit Sharma

Reputation: 35

it makes thread to run either in background without intrupting main work while true or run as main thread while false

Upvotes: 0

prt
prt

Reputation: 215

This issue is because different behaviour observed with daemon threads while running python code into python shell , let say Ipython in Spyder in my case vs running python file from command line like " python thread_example.py ".

Running file from command line gives expected behaviour.

One can refer this stackoverflow answer : Python daemon thread does not exit when parent thread exits

Upvotes: 1

Related Questions