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:
CreateThread
– creates a new thread.TerminateThread
– forcibly ends a thread.SuspendThread
/ResumeThread
– pause and resume execution.SetThreadPriority
– adjust scheduling priority.- Thread‑Local Storage (TLS) –
TlsAlloc
,TlsSetValue
,TlsGetValue
.
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
- Prefer
CreateThread
for simple scenarios; use_beginthreadex
when mixing C runtime libraries. - Avoid
TerminateThread
unless absolutely necessary – it can lead to resource leaks. - Use synchronization objects (events, mutexes, critical sections) to protect shared data.
- Set thread priorities sparingly; the scheduler normally handles most workloads.
- Clean up all handles with
CloseHandle
after a thread exits.