📜  GetCurrentThreadId c - C++ (1)

📅  最后修改于: 2023-12-03 15:00:54.426000             🧑  作者: Mango

GetCurrentThreadId in C/C++

GetCurrentThreadId is a function in Windows API that retrieves the thread identifier of the calling thread.

Syntax
DWORD GetCurrentThreadId(void);
Return value

The thread identifier of the calling thread.

Example
#include <Windows.h>
#include <stdio.h>

DWORD WINAPI ThreadFunc(LPVOID lpParam) {
    DWORD tid = GetCurrentThreadId();
    printf("Thread ID: %u\n", tid);
    return 0;
}

int main(void) {
    HANDLE hThread;
    DWORD dwThreadId;

    // Create a new thread
    hThread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, &dwThreadId);
    if (hThread == NULL) {
        printf("Failed to create thread.\n");
        return 1;
    }

    // Wait for the thread to finish
    WaitForSingleObject(hThread, INFINITE);

    // Close the handle
    CloseHandle(hThread);

    return 0;
}

In this example, a new thread is created using the CreateThread function. The thread function retrieves its thread identifier using the GetCurrentThreadId function and prints it to the console. After the thread completes, the handle is closed and the program exits.

Conclusion

GetCurrentThreadId is a useful function in Windows API for retrieving the thread identifier of the calling thread. It can be used in multithreaded applications to distinguish between different threads or to debug thread-related issues.