linuxwindowsmultithreadingoperating-systemhandle

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?


Solution

  • 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.