Python threading Module | current_thread() Method with Example

Python threading.current_thread() Method: Here, we are going to learn about the getName() method of threading Module in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 14, 2020

Python threading.current_thread() Method

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

Module:

    import threading

Syntax:

    current_thread()

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:

# 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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.