Search code examples
pythonmultithreadingdaemonfreeze

Why don't these daemon threads get killed?


I was learning about sharing data between threads and I stumbled upon this different problem. As far as I understand, daemon threads are killed upon completion of main thread. The simple code is below:

import threading
from time import sleep

def thread(Nr):
    global x
    lock.acquire()
    x = Nr
    print(x)
    sleep(4)
    print(x)
    lock.release()

    return 0

#################################################################################

x = 2
lock = threading.Lock()

for i in range(6):
    #print("Thread Nr: ", i)
    arg1 = i
    t = threading.Thread(target = thread, args = (arg1,), name = arg1)
    t.setDaemon(True)
    print("new thread started : %s" % (str(threading.current_thread().ident)))    
    t.start()
    sleep(1)

print("Main thread end")

I'm starting 6 threads and this is my output in IDLE python 3.7.2:

new thread started : 940
0
new thread started : 940
new thread started : 940
new thread started : 940
new thread started : 9400

1
new thread started : 940
Main thread end
>>> 1
2
2
3
3
4
4
5
5

So, as you can see the threads continue to run after the main thread even if they are deamonic. One interesting thing I discovered is that they dont print anything after "Main thread end" if they are run from windows cmd instead of IDLE.

Does anyone know what is happening here?

Thanks :)


Solution

  • They do, but not in your IDLE.

    Running things in your IDLE is not something you should rely on. What matters is your command prompt. For example, you cant really use Multiprocessing library with your IDLE.

    As far as your IDLE is concerned, I believe the threads continiue, because in shell(IDLE), you dont actually finish your script/program. The very fact you can add new commands, shows, your program is still running - in a form of waiting for your next input.

    Shell is like program with (see below) at the end of your script

    while True:
        exec(raw_input('>>> '))
    

    That means, your main thread is still running and so whether you set daemon true or false doesnt matter

    If you want to see for yourself, add after your print

    exit(0)
    

    and see what happens

    enter image description here