Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the thread ID from a thread

In C# when debugging threads for example, you can see each thread's ID.

I couldn't find a way to get that same thread, programmatically. I could not even get the ID of the current thread (in the properties of the Thread.currentThread).

So, I wonder how does Visual Studio get the IDs of the threads, and is there a way to get the handle of the thread with id 2345, for example?

like image 520
LolaRun Avatar asked Nov 05 '09 09:11

LolaRun


People also ask

How do I get the thread ID in Python?

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

How do I find thread ID in Linux?

Method One: PSIn ps command, "-T" option enables thread views. The following command list all threads created by a process with <pid>. The "SID" column represents thread IDs, and "CMD" column shows thread names.

Does a thread have an ID?

In some threads implementations, the thread ID is a 4-byte integer that starts at 1 and increases by 1 every time a thread is created. This integer can be used in a non-portable fashion by an application.

What is the thread ID?

Thread Id is a long positive integer that is created when the thread was created. During the entire lifecycle of a thread, the thread ID is unique and remains unchanged. It can be reused when the thread is terminated.


2 Answers

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.

like image 54
Blindy Avatar answered Sep 24 '22 13:09

Blindy


In C# when debugging threads for example, you can see each thread's ID.

This will be the Ids of the managed threads. ManagedThreadId is a member of Thread so you can get the Id from any Thread object. This will get you the current ManagedThreadID:

Thread.CurrentThread.ManagedThreadId 

To get an OS thread by its OS thread ID (not ManagedThreadID), you can try a bit of linq.

int unmanagedId = 2345; ProcessThread myThread = (from ProcessThread entry in Process.GetCurrentProcess().Threads    where entry.Id == unmanagedId     select entry).First(); 

It seems there is no way to enumerate the managed threads and no relation between ProcessThread and Thread, so getting a managed thread by its Id is a tough one.

For more details on Managed vs Unmanaged threading, see this MSDN article.

like image 43
badbod99 Avatar answered Sep 26 '22 13:09

badbod99