Getting the Thread Id from a Thread

How to obtain a Thread id in Python?

threading.get_ident() works, or threading.current_thread().ident (or threading.currentThread().ident for Python < 2.6).

How to get thread id of a pthread in linux c program?

pthread_self() function will give the thread id of current thread.

pthread_t pthread_self(void);

The pthread_self() function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np() to return an integral identifier for the thread.

NOTE:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();

is significantly faster than these calls, but provides the same behavior.

pthread_id_np_t   tid;
pthread_t self;
self = pthread_self();
pthread_getunique_np(&self, &tid);

Retrieving thread id from a thread object before starting the thread in python

As I commented, the documentation states clearly that ident (and native_id) is None before the thread has started. See https://docs.python.org/3/library/threading.html?highlight=ident#threading.Thread.ident

Here's a way you can get the ident or native_id before the thread has done anything useful, using a semaphore which the main code acquires before starting the thread, and releases once main is ready for the thread to continue.

import threading
import time

def threadfunc(word1,word2):
global s
print( f"Thread Started" )
print( f"Thread Acquiring sempahore" )
s.acquire()
print( f"Thread Acquired sempahore" )
print( f"{word1}, {word2}" )
# do something useful ....
time.sleep(0.1)
# wrap-up
print( f"Thread Releasing sempahore" )
s.release()
print( f"Thread Released sempahore" )
print( "Thread Finished" )

s = threading.Semaphore()

print( f"Main Acquiring sempahore" )
s.acquire()
print( f"Main Acquired sempahore" )

t = threading.Thread(
name='mythread'
,target=threadfunc
,args=("hello","world")
)

# I want the id here
id = t.ident

print( f"Thread id before start: {id}" )

print( "Main starting thread" )
t.start()
print( "Main started thread" )

id1 = t.ident

print( f"Thread id after start: {id1}" )

print( f"Main Releasing sempahore" )
s.release()
print( f"Main Released sempahore" )

t.join()
print( "Main Finished" )

Result:

Main Acquiring sempahore
Main Acquired sempahore
Thread id before start: None
Main starting thread
Thread Started
Main started thread
Thread Acquiring sempahore
Thread id after start: 16932
Main Releasing sempahore
Main Released sempahore
Thread Acquired sempahore
hello, world
Thread Releasing sempahore
Thread Released sempahore
Thread Finished
Main Finished

Semaphore documentation is here https://docs.python.org/3/library/threading.html?highlight=semaphore#threading.Semaphore

Other synchronization methods are available, e.g. Lock, RLock, conditions, etc, and could easily be used instead of Sempahore - all are on the doc link above.

How can I get the thread id of the threads of the servlet?

It is not actually a meaningful thing to ask for.

Threads don't belong to a servlet. Rather, they belong to the web container and are used to run requests ... which at certain points involves running servlet methods. A servlet method can of course find out what the current thread is ... but then so can any method.

It is also possible that the web container might use thread groups in a way that allows you to determine that certain threads are used for certain things. But that would be highly implementation specific.

If that's not what you mean, then please refine your question.


What I mean is to get the threads that executing the code of the servlet.

Do you mean currently executing the code of the servlet?

Then I think that the answer is simply - "This is not possible".

It is not possible within a running program for one application thread to find out what code another thread is executing. This kind of thing can only be found using a debug agent ... while all application threads are stopped.


I want a thread id inserted at the front of each line of the log so that I can trace the activity of each thread.

(Well why didn't you simply ask that in the first place??)

A log4j LoggingEvent contains the name of the thread that created the event. You can use a %t in a pattern layout to include the thread name in a log file. You could also write your own custom Appender to filter the events into different "streams" based on the event's thread name.

The thread id is not available for logging ... unless you explicitly insert it into (for example) the log message string.

Getting the thread ID

Use GetCurrentThreadId() or ManagedThreadId() to get the thread ID:

int threadID = (int)AppDomain.GetCurrentThreadId();
int managedThreadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("ThreadId = " + threadID);
Console.WriteLine("ManagedThreadId = " + managedThreadId);

Have a look at Stack Overflow question Getting the thread ID from a thread.

Getting the thread ID from a thread

GetThreadId returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.

GetCurrentThreadId returns the ID of the current thread.

GetCurrentThreadId has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId property.

How can i get current thread id in function that runs in thread?

It doesn't "work" for so many reasons. First of all make sure it compiles. Second, a thread is not like a simple class like a string. You cannot copy threads; you can only move threads. What you're doing is trying to initialize an "empty" thread to then copy another thread on top of it. What you can do, if you want an array, is to use pointers instead. To get current thread id, you have to use this_thread::get_id();

#include <thread>
#include <iostream>

#define NUM_TH 4

using namespace std;

void printhello() {
auto th_id = this_thread::get_id();
cout << "Hello world! Thread ID, "<< th_id << endl;
}

int main() {
thread* th[NUM_TH];

for (int i = 0; i < NUM_TH; i++)
{
th[i] = new thread(printhello);
th[i]->join();
}
}

How to get thread id from a thread pool?

Using Thread.currentThread():

private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}


Related Topics



Leave a reply



Submit