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