Process & Thread Management
The Windows API (Win32) Fundamentals · Windows Programming track
11 min read
In this module
Creating and Controlling Processes and Threads
The Win32 API gives you a dense set of functions for creating processes, managing threads, and synchronising their execution — the building blocks of every multitasking Windows application. Knowing CreateProcess in detail, and knowing the synchronisation primitives cold, is what separates correct concurrent Windows code from code that works until it doesn't.
CreateProcess: All 10 Parameters
CreateProcess is one of the most important Win32 functions. Let us examine every parameter:
BOOL CreateProcess( LPCSTR lpApplicationName, // 1. EXE path (optional, can be NULL) LPSTR lpCommandLine, // 2. Full command line (mutable!) LPSECURITY_ATTRIBUTES lpProcessAttributes, // 3. Process security LPSECURITY_ATTRIBUTES lpThreadAttributes, // 4. Thread security BOOL bInheritHandles, // 5. Handle inheritance flag DWORD dwCreationFlags, // 6. Creation flags LPVOID lpEnvironment, // 7. Environment block (NULL = inherit) LPCSTR lpCurrentDirectory, // 8. Working directory (NULL = inherit) LPSTARTUPINFO lpStartupInfo, // 9. Window/IO configuration LPPROCESS_INFORMATION lpProcessInformation // 10. Output handles);Parameter 1 & 2: Application and Command Line
// Method 1: Application name + command lineCreateProcess("C:\\Windows\\System32\\cmd.exe", // lpApplicationName "/c dir", // lpCommandLine ...);
// Method 2: NULL application name, full path in command line (most common)char cmdLine[] = "cmd.exe /c dir"; // MUST be mutable (not a string literal)CreateProcess(NULL, cmdLine, ...); // Searches PATH for cmd.exeWhen lpApplicationName is NULL, Windows parses lpCommandLine to find the executable, searching the current directory and PATH. The command line buffer MUST be writable - CreateProcess may modify it temporarily.
Parameter 6: Creation Flags
// Common creation flags (can be combined with |)CREATE_NEW_CONSOLE // New console windowCREATE_NO_WINDOW // No console window at allCREATE_SUSPENDED // Primary thread starts suspendedCREATE_NEW_PROCESS_GROUP // New process group (for Ctrl+C handling)DETACHED_PROCESS // Not attached to parent's consoleDEBUG_PROCESS // Become the debugger of the childCREATE_UNICODE_ENVIRONMENT // lpEnvironment uses wide charactersEXTENDED_STARTUPINFO_PRESENT // lpStartupInfo is STARTUPINFOEX
// Priority class flagsIDLE_PRIORITY_CLASS // Priority 4BELOW_NORMAL_PRIORITY_CLASS // Priority 6NORMAL_PRIORITY_CLASS // Priority 8 (default)ABOVE_NORMAL_PRIORITY_CLASS // Priority 10HIGH_PRIORITY_CLASS // Priority 13REALTIME_PRIORITY_CLASS // Priority 24 (dangerous!)Parameters 9 & 10: Startup Info and Process Info
STARTUPINFO si = { .cb = sizeof(STARTUPINFO) };
// Optionally configure I/O redirectionsi.dwFlags = STARTF_USESTDHANDLES;si.hStdInput = hReadPipe; // Redirect stdin from pipesi.hStdOutput = hWriteFile; // Redirect stdout to filesi.hStdError = GetStdHandle(STD_ERROR_HANDLE);
// Or configure window positionsi.dwFlags = STARTF_USEPOSITION | STARTF_USESIZE;si.dwX = 100; si.dwY = 100;si.dwXSize = 800; si.dwYSize = 600;
PROCESS_INFORMATION pi; // Output structure// pi.hProcess - Handle to the new process// pi.hThread - Handle to the primary thread// pi.dwProcessId - Process ID// pi.dwThreadId - Primary thread IDCreateProcess returns two handles in the PROCESS_INFORMATION structure: one for the process and one for its primary thread. You MUST close both handles with CloseHandle() when done, or you will leak kernel objects. The process and thread continue to exist even after you close the handles - closing handles just releases your reference, it does not terminate them.
Thread Creation and Management
CreateThread
HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, // NULL for default SIZE_T dwStackSize, // 0 = default (1 MB) LPTHREAD_START_ROUTINE lpStartAddress, // Thread function LPVOID lpParameter, // Argument to thread function DWORD dwCreationFlags, // 0 or CREATE_SUSPENDED LPDWORD lpThreadId // Output: thread ID (optional));
// Thread function signatureDWORD WINAPI ThreadProc(LPVOID lpParameter) { // Do work... return 0; // Exit code}Thread Lifecycle
Synchronisation Primitives
Windows provides four primary synchronisation objects, plus critical sections for intra-process locking.
Critical Sections (User-Mode Only)
Critical sections are the fastest synchronisation primitive because they operate entirely in user mode when there is no contention:
CRITICAL_SECTION cs;InitializeCriticalSection(&cs);
// Thread-safe accessEnterCriticalSection(&cs); // Acquire (blocks if held by another thread)// ... critical section code ...LeaveCriticalSection(&cs); // Release
// Non-blocking attemptif (TryEnterCriticalSection(&cs)) { // ... acquired ... LeaveCriticalSection(&cs);} else { // ... someone else holds it, do something else ...}
DeleteCriticalSection(&cs); // CleanupCritical sections use a spin count before falling back to a kernel wait, making them very efficient for short-held locks. They cannot be used across processes.
Mutexes (Cross-Process)
// Create a named mutex (accessible from other processes)HANDLE hMutex = CreateMutex(NULL, FALSE, "Global\\MyAppMutex");// FALSE = not initially owned
// Acquire (wait for mutex to be released by current owner)WaitForSingleObject(hMutex, INFINITE);// ... protected code ...ReleaseMutex(hMutex);
// From another process:HANDLE hMutex = OpenMutex(SYNCHRONIZE, FALSE, "Global\\MyAppMutex");WaitForSingleObject(hMutex, 5000); // Wait up to 5 secondsMutexes are kernel objects with overhead for every acquire/release, but they work across processes and have ownership tracking (only the owning thread can release).
Semaphores
Semaphores allow a limited number of threads to access a resource simultaneously:
// Create a semaphore with initial count 3, max 3// (allows up to 3 concurrent accessors)HANDLE hSem = CreateSemaphore(NULL, 3, 3, "MySemaphore");
// Acquire (decrements count; blocks if count is 0)WaitForSingleObject(hSem, INFINITE);// ... access shared resource ...
// Release (increments count by 1)ReleaseSemaphore(hSem, 1, NULL);Events
Events signal when something has happened:
// Manual-reset event: stays signaled until explicitly resetHANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, "MyEvent");// TRUE = manual reset, FALSE = initial state (non-signaled)
// Worker thread: wait for signalWaitForSingleObject(hEvent, INFINITE);// Event was signaled, proceed...
// Signal the event (wakes ALL waiting threads for manual-reset)SetEvent(hEvent);
// Reset the event (must be done manually for manual-reset events)ResetEvent(hEvent);
// Auto-reset event: automatically resets after releasing ONE waiterHANDLE hAutoEvent = CreateEvent(NULL, FALSE, FALSE, NULL);SetEvent(hAutoEvent); // Wakes exactly one waiting thread, then auto-resetsA manual-reset event stays signalled until ResetEvent() is called, allowing ALL waiting threads to proceed. An auto-reset event automatically returns to non-signalled after releasing exactly ONE thread. Auto-reset events are useful for producer-consumer patterns where one producer wakes one consumer. Manual-reset events are useful for broadcasting (e.g., signalling that initialisation is complete).
WaitForSingleObject and WaitForMultipleObjects
These are the fundamental wait functions:
// Wait for one objectDWORD result = WaitForSingleObject(hObject, dwMilliseconds);// Returns:// WAIT_OBJECT_0 (0) - Object is signaled// WAIT_TIMEOUT (258) - Timeout expired// WAIT_ABANDONED (0x80) - Mutex was abandoned (owning thread died)// WAIT_FAILED (0xFFFFFFFF) - Error (call GetLastError())
// Wait for multiple objectsHANDLE handles[] = { hProcess, hEvent, hMutex };DWORD result = WaitForMultipleObjects( 3, // Count handles, // Array of handles FALSE, // FALSE = wait for ANY, TRUE = wait for ALL 5000 // Timeout in ms (INFINITE for no timeout));// Returns:// WAIT_OBJECT_0 + index - Which handle was signaled// WAIT_TIMEOUT - Timeout expired// WAIT_ABANDONED_0 + index - Which mutex was abandonedPractical Example: Thread Pool Pattern
#define WORKER_COUNT 4
typedef struct { int taskId; HANDLE completionEvent;} WorkItem;
DWORD WINAPI Worker(LPVOID param) { WorkItem *item = (WorkItem *)param; printf("Processing task %d\n", item->taskId); Sleep(1000); // Simulate work SetEvent(item->completionEvent); // Signal completion return 0;}
int main(void) { WorkItem items[WORKER_COUNT]; HANDLE threads[WORKER_COUNT]; HANDLE events[WORKER_COUNT];
for (int i = 0; i < WORKER_COUNT; i++) { events[i] = CreateEvent(NULL, TRUE, FALSE, NULL); items[i].taskId = i; items[i].completionEvent = events[i]; threads[i] = CreateThread(NULL, 0, Worker, &items[i], 0, NULL); }
// Wait for ALL tasks to complete WaitForMultipleObjects(WORKER_COUNT, events, TRUE, INFINITE); printf("All tasks completed!\n");
for (int i = 0; i < WORKER_COUNT; i++) { CloseHandle(threads[i]); CloseHandle(events[i]); } return 0;}Thread Pools (Modern API)
Windows Vista+ provides a built-in thread pool API that is more efficient than manual thread management:
// Submit work to the system thread poolPTP_WORK work = CreateThreadpoolWork(WorkCallback, context, NULL);SubmitThreadpoolWork(work);
// Wait for completionWaitForThreadpoolWorkCallbacks(work, FALSE);CloseThreadpoolWork(work);
void CALLBACK WorkCallback(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work) { // This runs on a thread pool thread // Do your work here}The system thread pool manages thread creation, destruction, and reuse automatically, adapting to the current workload. It's substantially more efficient than spinning threads up and down by hand.
Process creation and thread synchronisation are the foundations of concurrent Windows programming. These primitives are used directly in systems code and underpin every higher-level concurrency framework Windows provides.