Python threading get_native_id() Method with Example

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

Python threading.get_native_id() Method

The threading.get_native_id() is an inbuilt method of the threading module, it is used to return the native Thread ID of the current thread which is assigned by the kernel. This non-negative number can be used to uniquely identify this particular thread system-wide; until the thread terminates, after which its value may be recycled by the OS. It is available from version 3.8.

Module

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

import threading

Syntax

The following is the syntax of get_native_id() method:

get_ident()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is <class 'int'>, it returns a number that acts as a native thread identifier for the current thread.

Example of threading.get_native_id() Method in Python

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

import time
import threading

def thread_1(i):
    time.sleep(5)
    print("Native thread identifier for Thread-1:", threading.get_native_id())
    print('Value by Thread 1:', i)

def thread_2(i):
    print("Native thread identifier for Thread-2:", threading.get_native_id())
    print('Value by Thread 2:', i)
    
def thread_3(i):
    time.sleep(4)
    print("Native thread identifier for Thread-3:", threading.get_native_id())
    print("Value by Thread 3:", 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,))

print("Native thread identifier for main-thread:", threading.get_native_id() )

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

Output

Native thread identifier for main-thread: 19156
Native thread identifier for Thread-2: 4296
Value by Thread 2: 20
Native thread identifier for Thread-3: 6776
Value by Thread 3: 30
Native thread identifier for Thread-1: 17312
Value by Thread 1: 10



Comments and Discussions!

Load comments ↻





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