Python threading main_thread() Method with Example

Python threading.main_thread() Method: In this tutorial, we will learn about the main_thread() method of threading module in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 23, 2023

Python threading.main_thread() Method

The threading.main_thread() is an inbuilt method of the threading module, it is used to return the main Thread object. It is the thread from which the Python interpreter has started, in normal conditions.

Module

The following module is required to use main_thread() method:

import threading

Syntax

The following is the syntax of main_thread() method:

main_thread()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is <class 'threading._MainThread'>, it returns the main Thread object.

Example of threading.main_thread() Method in Python

# Python program to explain the
# use of  main_thread()  method in Threading Module

import time
import threading

def thread_1(i):
    time.sleep(5)
    print("Value by Thread-:",i)
    
def thread_2(i):
    print("Value by Thread-2:",i)
    
def thread_3(i):
    time.sleep(4)
    print("Value by Thread-3:",i)
    
def thread_4(i):
    time.sleep(1)
    print("Value by Thread-4:",i)

# Creating sample threads 
thread1 = threading.Thread(target=thread_1, args=(10,))
thread2 = threading.Thread(target=thread_2, args=(20,))
thread3 = threading.Thread(target=thread_3, args=(30,))
thread4 = threading.Thread(target=thread_4, args=(50,))

print("Main thread for the given program:", threading.main_thread())

# Starting the threads
thread1.start()
thread2.start()
thread3.start()
thread4.start()

Output

Main thread for the given program: <_MainThread(MainThread, started 140269857195776)>
Value by Thread-2: 20
Value by Thread-4: 50
Value by Thread-3: 30
Value by Thread-: 10



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.