import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(5)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
logging.info("Main : before creating thread")
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
logging.info("Main : before running thread")
x.start()
logging.info("Main : wait for the thread to finish")
# x.join()
logging.info("Main : all done")
The output is
08:31:35: Main : before creating thread
08:31:35: Main : before running thread
08:31:35: Thread 1: starting
08:31:35: Main : wait for the thread to finish
08:31:35: Main : all done
08:31:45: Thread 1: finishing
That happens as part of the thread spawning. Thatâs not a problem.
I do notice, though, that youâre not joining the thread here. So my guess is that youâre expecting the other thread to continue, but itâs not? Thatâs what daemon=True does - it wonât continue once the main thread (and any other non-daemon threads) finishes. Are you sure you want that option?
The main thread finishes, but the thread of function âthread_functionâ seem continue in my code when running as a ipynb file.
The output is
08:31:35: Main : before creating thread
08:31:35: Main : before running thread
08:31:35: Thread 1: starting
08:31:35: Main : wait for the thread to finish
08:31:35: Main : all done
08:31:45: Thread 1: finishing
Okay, this is VERY confusing. You have edited your posts in a way that completely changes the meaning. What exactly is happening, what do you expect to happen, and what do you want to happen?
Please, donât edit your posts in this way. Respond with further information.
08:31:35: Main : before creating thread
08:31:35: Main : before running thread
08:31:35: Thread 1: starting
08:31:35: Main : wait for the thread to finish
08:31:35: Main : all done
But actually the output is
08:31:35: Main : before creating thread
08:31:35: Main : before running thread
08:31:35: Thread 1: starting
08:31:35: Main : wait for the thread to finish
08:31:35: Main : all done
08:31:45: Thread 1: finishing
This would be one of rare occasions where screenshots would be helpful. With .ipynb file you mean an interactive notebook, right? If so, this is the expected behaviour. Just because a single cell finishes executing doesnât mean that the python interpreter gets shut down, so background threads continue to run.