Win32 Threading

Overview

Win32 provides a robust set of functions for creating and managing threads. Threads allow concurrent execution within a single process, enabling responsive UI, background processing, and efficient CPU utilization.

Key Functions

Example: Creating a Worker Thread

C
C++
Output
#include <windows.h>
#include <stdio.h>

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

int main() {
    HANDLE hThread = CreateThread(
        NULL, 0, Worker, NULL, 0, NULL);
    if (hThread == NULL) {
        printf("Failed to create thread.\n");
        return 1;
    }
    WaitForSingleObject(hThread, INFINITE);
    CloseHandle(hThread);
    printf("Main thread exiting.\n");
    return 0;
}
#include <windows.h>
#include <iostream>

DWORD WINAPI Worker(LPVOID) {
    for (int i = 0; i < 5; ++i) {
        std::cout << "Worker thread: " << i << std::endl;
        Sleep(500);
    }
    return 0;
}

int main() {
    HANDLE hThread = CreateThread(
        nullptr, 0, Worker, nullptr, 0, nullptr);
    if (!hThread) {
        std::cerr << "Failed to create thread." << std::endl;
        return 1;
    }
    WaitForSingleObject(hThread, INFINITE);
    CloseHandle(hThread);
    std::cout << "Main thread exiting." << std::endl;
    return 0;
}
Worker thread: 0
Worker thread: 1
Worker thread: 2
Worker thread: 3
Worker thread: 4
Main thread exiting.

Thread Synchronization

To avoid race conditions, use synchronization primitives such as CRITICAL_SECTION, Mutex, or Event. Below is a simple critical section example.

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

CRITICAL_SECTION cs;

DWORD WINAPI Increment(LPVOID lpParam) {
    for (int i = 0; i < 1000000; ++i) {
        EnterCriticalSection(&cs);
        (*(int*)lpParam)++;
        LeaveCriticalSection(&cs);
    }
    return 0;
}

int main() {
    InitializeCriticalSection(&cs);
    int counter = 0;
    HANDLE h1 = CreateThread(NULL,0,Increment,&counter,0,NULL);
    HANDLE h2 = CreateThread(NULL,0,Increment,&counter,0,NULL);
    WaitForMultipleObjects(2,(HANDLE[]){h1,h2},TRUE,INFINITE);
    DeleteCriticalSection(&cs);
    printf("Final counter value: %d\n",counter);
    return 0;
}