GetCurrentThread
HANDLE GetCurrentThread(void);
Parameters
None.
Return Value
HANDLE
The return value is a handle to the current thread. This handle is pseudohandle. The pseudohandle is valid only within the calling process and can be used only for certain functions, such as those that require a thread handle as a parameter.
Remarks
A pseudohandle is a special value that refers to the current object (process or thread). This handle is valid only within the calling process. When a thread handle is returned by a function such as this, it is a pseudohandle.
The calling process can use the pseudohandle returned by GetCurrentThread to specify the current thread in a call to any function that requires a handle to a thread. The thread handle is valid until the thread is terminated. For some system functions, the pseudohandle is (HANDLE)-2
. A thread can also obtain a handle to itself by calling the OpenThread function with the identifier of the thread.
The pseudohandle is useful when you need a handle to the current thread but do not have an explicit handle available. For example, you can use the pseudohandle returned by GetCurrentThread to set the thread's priority level by passing it to the SetThreadPriority function.
Requirements
Minimum supported client | Windows 2000 Professional |
Minimum supported server | Windows 2000 Server |
Header | Winuser.h (include Windows.h) |
Library | Use Kernel32.lib |
DLL | Kernel32.dll |
Example
The following example demonstrates how to use GetCurrentThread to obtain a handle to the current thread and then use that handle to set the thread's priority.
// This code snippet is for illustrative purposes only and may not be
// a complete, runnable example. It assumes that the necessary headers
// and libraries are included.
#include <windows.h>
#include <iostream>
int main() {
HANDLE hThread = GetCurrentThread();
if (hThread != NULL) {
// Get the current priority
int currentPriority = GetThreadPriority(hThread);
std::wcout << L"Current thread priority: " << currentPriority << std::endl;
// Attempt to set a higher priority (e.g., THREAD_PRIORITY_ABOVE_NORMAL)
// Note: Setting priority requires appropriate permissions.
BOOL setPrioritySuccess = SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);
if (setPrioritySuccess) {
std::wcout << L"Successfully set thread priority to ABOVE_NORMAL." << std::endl;
currentPriority = GetThreadPriority(hThread); // Verify
std::wcout << L"New thread priority: " << currentPriority << std::endl;
} else {
DWORD error = GetLastError();
std::wcerr << L"Failed to set thread priority. Error code: " << error << std::endl;
}
} else {
std::wcerr << L"Failed to get current thread handle." << std::endl;
}
return 0;
}