2

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.

prt
  • 205
  • 3
  • 11
  • 2
    It's the opposite actually: daemon thread don't keep running when the main thread exists. Also this code works me (=the program exists when daemon=True and the opposite when daemon=False) – Tomer Arazy Jan 05 '20 at 16:01
  • but for me it just keep printing in both the cases. in daemon case should it stop printing ?? – prt Jan 05 '20 at 17:40
  • Yes. Which version of python are you using? – Tomer Arazy Jan 06 '20 at 10:29
  • Hey Tomer I figured out actully , It is because different behaviour of running python code into python shell vs running python file from command line . This is the refererance answer : https://stackoverflow.com/questions/21843916/python-daemon-thread-does-not-exit-when-parent-thread-exits. Thanks for your help. – prt Jan 06 '20 at 12:46

2 Answers2

1

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

prt
  • 205
  • 3
  • 11
0

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