Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting thread id of current method call

People also ask

How do I find my current thread ID?

In the run() method, we use the currentThread(). getName() method to get the name of the current thread that has invoked the run() method. We use the currentThread(). getId() method to get the id of the current thread that has invoked the run() method.

How do I get current thread?

A thread can be created by implementing the Runnable interface and overriding the run() method. The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread. This method requires no parameters.

How does a running thread find its thread ID?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.

How do I get the current thread ID in Python?

In Python 3.3+, you can use threading. get_ident() function to obtain the thread ID of a thread. threading. get_ident() returns the thread ID of the current thread.


NSLog(@"%@", [NSThread currentThread]);

#include <pthread.h>
...
mach_port_t machTID = pthread_mach_thread_np(pthread_self());
NSLog(@"current thread: %x", machTID);

In Swift 5

print("Current thread \(Thread.current)")

In Swift

print("Current thread \(NSThread.currentThread())")

In Swift4

print("\(Thread.current)")

you can hack something up like this (this just prints pretty, but you can go ahead and split until you get the number):

+ (NSString *)getPrettyCurrentThreadDescription {
    NSString *raw = [NSString stringWithFormat:@"%@", [NSThread currentThread]];

    NSArray *firstSplit = [raw componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{"]];
    if ([firstSplit count] > 1) {
        NSArray *secondSplit     = [firstSplit[1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"}"]];
        if ([secondSplit count] > 0) {
            NSString *numberAndName = secondSplit[0];
            return numberAndName;
        }
    }

    return raw;
}

NSLog prints to the console a number (in square brackets after the colon) identifying the thread on which it was called.

NSLog output