Python - Main Thread



Every Python program has at least one thread of execution called the main thread. The main thread by default is a non-daemon thread.

Sometimes we may need to create additional threads in our program in order to execute the code concurrently.

Here is the syntax for creating a new thread −

object = threading.Thread(target, daemon)

The Thread() constructor creates a new object. By calling the start() method, the new thread starts running, and it calls automatically a function given as argument to target parameter which defaults to run. The second parameter is "daemon" which is by default None.

Example

from time import sleep
from threading import current_thread
from threading import Thread

# function to be executed by a new thread
def run():
   # get the current thread
   thread = current_thread()
   # is it a daemon thread?
   print(f'Daemon thread: {thread.daemon}')

# create a new thread
thread = Thread(target=run)

# start the new thread
thread.start()

# block for a 0.5 sec
sleep(0.5)

It will produce the following output

Daemon thread: False

So, creating a thread by the following statement −

t1=threading.Thread(target=run)

This statement creates a non-daemon thread. When started, it calls the run() method.

Advertisements