Start a Thread
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
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,))
logging.info("Main : before running thread")
x.start()
logging.info("Main : wait for the thread to finish")
x.join()
logging.info("Main : all done")
Daemon Threads
Python threading
has a more specific meaning for daemon
. A daemon
thread will shut down immediately when the program exits. One way to think about these definitions is to consider the daemon
thread a thread that runs in the background without worrying about shutting it down.
If a program is running Threads
that are not daemons
, then the program will wait for those threads to complete before it terminates. Threads
that are daemons, however, are just killed wherever they are when the program is exiting.