Introduction
Threads are the basic unit of execution within a process. The Windows kernel provides a rich set of APIs to create, manage, and synchronize threads.
Creating a Thread
Use CreateThread or the higher‑level _beginthreadex to start a new thread.
#include <windows.h>
#include <process.h>
unsigned __stdcall ThreadFunc(void* param) {
// Thread work here
return 0;
}
int main() {
HANDLE hThread = (HANDLE)_beginthreadex(
nullptr, 0, ThreadFunc, nullptr, 0, nullptr);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
Thread Lifecycle
- Created – The thread is instantiated but not yet scheduled.
- Ready – The thread is eligible to run.
- Running – The thread is currently executing on a processor.
- Blocked – The thread is waiting for a resource (e.g., I/O, synchronization object).
- Terminated – The thread has finished execution and can be cleaned up.
Synchronization Primitives
Common primitives for thread coordination include:
| Primitive | Description |
|---|---|
| CRITICAL_SECTION | Fast, user‑mode mutual exclusion. |
| Mutex | Kernel‑mode exclusive lock, can be shared across processes. |
| Event | Signaling mechanism for one‑to‑many or many‑to‑many. |
| Semaphore | Counts resource availability. |
Best Practices
- Prefer
_beginthreadexwhen using the C runtime library. - Avoid blocking the UI thread; use worker threads for long operations.
- Minimize the duration a thread holds a lock to reduce contention.
- Use thread pool APIs (
CreateThreadpoolWork) for scalable workloads.