Windows Threads
Threads are the basic unit of execution in Windows. They enable concurrent execution of code within a single process, sharing the same address space while maintaining separate registers, stack, and thread‑local storage.
Overview
Code Example
API Reference
Key Concepts
- Thread Creation – Use
CreateThread
or_beginthreadex
for C/C++. - Thread Priorities – Ranges from
THREAD_PRIORITY_LOWEST
toTHREAD_PRIORITY_HIGHEST
. - Synchronization – Critical sections, mutexes, events, semaphores, and condition variables.
- Thread Local Storage (TLS) –
TlsAlloc
,TlsSetValue
,TlsGetValue
. - Termination & Cleanup – Use
ExitThread
or return from the thread function; always free resources.
Creating a Simple Worker Thread (C++)
#include <windows.h>
#include <iostream>
DWORD WINAPI Worker(LPVOID lpParam) {
int id = *reinterpret_cast<int*>(lpParam);
std::cout << "Thread " << id << " started.\n";
// Simulate work
Sleep(2000);
std::cout << "Thread " << id << " finished.\n";
return 0;
}
int main() {
const int threadCount = 3;
HANDLE hThreads[threadCount];
int ids[threadCount];
for (int i = 0; i < threadCount; ++i) {
ids[i] = i + 1;
hThreads[i] = CreateThread(
nullptr, // default security attributes
0, // default stack size
Worker, // thread function
&ids[i], // parameter to thread function
0, // default creation flags
nullptr); // receive thread identifier
if (hThreads[i] == nullptr) {
std::cerr << "Failed to create thread " << i+1 << "\n";
}
}
// Wait for all threads to finish
WaitForMultipleObjects(threadCount, hThreads, TRUE, INFINITE);
for (auto h : hThreads) CloseHandle(h);
return 0;
}
Compile with cl /EHsc thread_demo.cpp
and run to see concurrent output.
Selected API Functions
Function | Header | Synopsis |
---|---|---|
CreateThread |
windows.h | Creates a new thread. |
ExitThread |
windows.h | Terminates the calling thread. |
WaitForSingleObject |
windows.h | Waits until the specified object is signaled. |
InitializeCriticalSection |
synchapi.h | Initializes a critical section object. |
For a full reference, visit API Reference.
© 2025 Microsoft. All rights reserved.