Thread Handles and Thread IDs

Last reviewed: September 25, 1995
Article ID: Q127992
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with:

        - Microsoft Windows NT versions 3.5 and 3.51
        - Microsoft Windows 95 version 4.0
    

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


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: September 25, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.