Python threading current_thread() Method with Example

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

Python threading.current_thread() Method

The threading.current_thread() is an inbuilt method of the threading module, it is used to return the current Thread object, which corresponds to the caller's thread of control.

Module

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

import threading

Syntax

The following is the syntax of current_thread() method:

current_thread()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is a Thread class object, it returns the current Thread object active at the moment.

Example of threading.current_thread() Method in Python

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

import time
import threading

def thread_1(i):
    time.sleep(2)
    print("Active current thread right now:", (threading.current_thread()))
    print('Value by Thread 1:', i)

def thread_2(i):
    time.sleep(5)
    print("Active current thread right now:", (threading.current_thread()))
    print('Value by Thread 2:', i)
    
def thread_3(i):
    print("Active current thread right now:", (threading.current_thread()))
    print("Value by Thread 3:", i)
    
# Creating sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))
thread3 = threading.Thread(target=thread_3, args=(3,))

print("Active current thread right now:", (threading.current_thread()))
#3 Initially it is the main thread that is active

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

Output

Active current thread right now: <_MainThread(MainThread, started 140048551704320)>
Active current thread right now: <Thread(Thread-3, started 140048508823296)>
Value by Thread 3: 3
Active current thread right now: <Thread(Thread-1, started 140048525608704)>
Value by Thread 1: 1
Active current thread right now: <Thread(Thread-2, started 140048517216000)>
Value by Thread 2: 2

Comments and Discussions!

Load comments ↻





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