I have the below python script:
script.py
from threading import Thread
def func():
while True:
pass
a = Thread(target=func)
a.start()
print('started the thread')
When running it from the terminal (python script.py
), it prints started the thread
and hangs in there. Coming from the C
background I know when the main thread completes the remaining threads are terminated as well. Is that not the case in Python? Will the python wait even without a call to a.join()
? Is there a concept of main thread in python or all threads are same?
CodePudding user response:
There is a "main thread" in Python, which is generally the thread that started the Python interpreter. Threads created by the threading
module have some layers of behavior on top of native OS threads. One of those behaviors is that when the interpreter exits, part of normal shutdown processing is that the main thread joins each non-daemon threading.Thread
- so, yes, Python normally waits for all other threads to end.
Whether daemon threading.Thread
s are forcefully shut down when Python exits is up to the OS, although I believe all major operating systems now do kill them.
If you want to exit the interpreter regardless of whether non-daemon threading.Thread
s are running, you need to kill the job, or call os._exit()
. Note the leading underscore! It's not recommended, but is there if you need it.