Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread ID vs. Thread Handle

What is the difference between a thread ID and a thread handle? Why both are needed? Is there a difference between Windows and Linux?

like image 708
FireAphis Avatar asked Feb 24 '11 08:02

FireAphis


People also ask

What is a 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.

Is thread ID same as process ID?

The thread ID of the initial (main) thread is the same as the process ID of the entire process. Thread IDs for subsequently created threads are distinct. They are allocated from the same numbering space as process IDs. Process IDs and thread IDs are sometimes also referred to collectively as task IDs.

How do you get thread handles?

If you have a thread identifier, you can get the thread handle by calling the OpenThread function. OpenThread enables you to specify the handle's access rights and whether it can be inherited.

Which thread is identified by thread ID of which data?

A thread ID is represented by the pthread_t data type.


2 Answers

Linux's pthread library does not, as far as I know, have a concept of a thread handle. pthread_create and other pthreads functions, return a thread ID.

Under Windows, the thread handle is different from the thread ID, in the same way that a file handle is different from a file name.

The thread handle is a token which allows you to do something with the thread (typically wait for it or kill it). Win32 has these tokens for lots of objects, and calls them HANDLE in general.

The token is essentially a pointer at the running (or stopped) thread and has a set of abilities associated with it, for example, you can have a handle which permits you to wait for, but not kill, a thread. In the same way, we can have a file handle which is read-only.

This level of indirection may or may not be useful, but it's the way Win32 does it, and it's broadly consistent with how it handles some other types of objects.

like image 54
MarkR Avatar answered Oct 17 '22 17:10

MarkR


The ID is the unique numeric identifier of the thread running in the system. A thread handle, like any kernel object handle, can be seen as a special type of reference counted pointer to the kernel object.

So in kernel space there is an object of type THREAD with ID = 12345

And because you want to do something with the thread you have a pointer in your address space called a threadID with value 44.

Please note that different handles to the same kernel object have different values (two pointers to one object) and that kernel objects can have handles in more than one process.

like image 6
Ritsaert Hornstra Avatar answered Oct 17 '22 18:10

Ritsaert Hornstra