Thread Handles and Thread IDs

ID: Q127992

4.00    | 3.50 3.51
WINDOWS | WINDOWS NT kbprg

The information in this article applies to:

The CreateThread() API is used to create threads. The API returns both a thread handle and a thread identifier (ID). The thread handle has full access rights to the thread object created. The thread ID uniquely identifies the thread on the system level while the thread is running. The ID can be recycled after the thread has been terminated. This relationship is similar to that of the process handle and the process ID (PID).

There is no way to get the thread handle from the thread ID. While there is an OpenProcess() API that takes a PID and returns the handle to the process, there is no corresponding OpenThread() that takes a thread ID and returns a thread handle.

The reason that the Win32 API does not make thread handles available this way is that it can cause damage to an application. The APIs that take a thread handle allow suspending/resuming threads, adjusting priority of a thread relative to its process, reading/writing registers, limiting a thread to a set of processors, terminating a thread, and so forth. Performing any one of these operations on a thread without the knowledge of the owning process is dangerous, and may cause the process to fail.

If you will need a thread handle, then you need to request it from the thread creator or the thread itself. Both the creator or the thread will have a handle to the thread and can give it to you using DuplicateHandle(). This requirement allows both applications to coordinate their actions.

NOTE: You can also take full control of the application by calling DebugActiveProcess(). Debuggers receive the thread handles for a process when the threads are created. These handles have THREAD_GET_CONTEXT, THREAD_SET_CONTEXT, and THREAD_SUSPEND_RESUME access to the thread.

Additional reference words: 3.50 4.00 95 KBCategory: kbprg KBSubcategory: BseProcThrd

Keywords          :  
Version           : winnt:3.5,3.51
Platform          : winnt

Last Reviewed: April 7, 1999