Python main thread

Python Main Thread

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

Sometimes, we need to create additional threads in our program to execute code concurrently.

The following 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 begins running and automatically calls the function given as the target parameter, which defaults to run. The second parameter is “daemon”, which defaults to 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)

This will produce the following output: –

Daemon thread: False

Therefore, a thread is created with the following statement: −

Daemon thread: False

Thus, a thread is created with the following statement: −

Daemon thread: False

line-numbers”>t1=threading.Thread(target=run)

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

Leave a Reply

Your email address will not be published. Required fields are marked *