Main Thread in Python

In every Python program, the main thread is the initial thread of execution and is non-daemon by default. Learn how to create additional threads to run code concurrently and enhance your program's efficiency.



Main Thread in Python

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

We can create additional threads in our program to execute code concurrently.

Syntax

Here is the syntax for creating a new thread:

Syntax

object = threading.Thread(target, daemon)

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

Example

Example

from time import sleep
from threading import current_thread, 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)
Output

Daemon thread: False

Creating a thread with the following statement:

Syntax

t1 = threading.Thread(target=run)

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