Thread Management

Overview

The Windows API provides a comprehensive set of functions for creating, controlling, and terminating threads. Threads allow a process to perform multiple tasks concurrently, improving responsiveness and throughput.

Key functions include:

Typical Usage Pattern

#include <windows.h>
#include <stdio.h>

DWORD WINAPI Worker(LPVOID param) {
    int id = *(int*)param;
    for (int i = 0; i < 5; ++i) {
        printf("Thread %d: iteration %d\n", id, i);
        Sleep(500);
    }
    return 0;
}

int main() {
    HANDLE hThread[2];
    int ids[2] = {1, 2};

    for (int i = 0; i < 2; ++i) {
        hThread[i] = CreateThread(
            NULL,               // default security attributes
            0,                  // default stack size
            Worker,             // thread function
            &ids[i],            // parameter to thread function
            0,                  // creation flags
            NULL);              // receive thread identifier
        if (hThread[i] == NULL) {
            fprintf(stderr, "CreateThread failed (%lu)\n", GetLastError());
            return 1;
        }
    }

    WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
    for (int i = 0; i < 2; ++i) CloseHandle(hThread[i]);
    return 0;
}

Best Practices