Thread Management
This section provides information on creating, managing, and synchronizing threads in Windows applications using the Win32 API.
Thread Creation
Creating a new thread is a fundamental operation for achieving concurrency. The primary function for this purpose is CreateThread
.
Creates a new thread within the calling process.
Parameters for CreateThread
Parameter | Type | Description |
---|---|---|
lpThreadAttributes |
LPSECURITY_ATTRIBUTES |
A pointer to a SECURITY_ATTRIBUTES structure that specifies the security descriptor for the new thread. If this parameter is NULL, the thread gets a default security descriptor. |
dwStackSize |
SIZE_T |
The initial size, in bytes, of the stack for the new thread. If this parameter is 0, the system uses the default stack size for the new thread. |
lpStartAddress |
LPTHREAD_START_ROUTINE |
A pointer to the application-defined function of the type TThreadStartRoutine . The thread executes this function until it returns. |
lpParameter |
LPVOID |
A pointer to a variable to be passed to the new thread. |
dwCreationFlags |
DWORD |
Flags that control the creation of the thread. |
lpThreadId |
LPDWORD |
A pointer to a variable that receives the thread identifier of the new thread. |
HANDLE CreateThread(
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in, optional] LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[out, optional] LPDWORD lpThreadId
);
std::thread
.
Thread Synchronization
When multiple threads access shared resources, synchronization mechanisms are crucial to prevent race conditions and ensure data integrity.
Common Synchronization Objects:
Mutexes
(Mutual Exclusion objects)Semaphores
Events
Critical Sections
Creates or opens a mutex object.
WaitForSingleObjectWaits until the specified object is in the signaled state or the time-out interval elapses.
CreateEventCreates or opens an event object.
Thread Information
You can retrieve various pieces of information about a thread, such as its ID, state, and priority.
GetCurrentThreadIdRetrieves the thread identifier of the calling thread.
GetThreadPriorityRetrieves the priority of the specified thread.
Thread Priority
Threads can be assigned different priority levels to influence their scheduling. A higher priority thread will preempt a lower priority thread.
SetThreadPrioritySets the priority of the specified thread. The priority must be within the range from THREAD_PRIORITY_LOWEST
to THREAD_PRIORITY_HIGHEST
.
Thread Priority Levels:
THREAD_PRIORITY_LOWEST
(-2)THREAD_PRIORITY_BELOW_NORMAL
(-1)THREAD_PRIORITY_NORMAL
(0)THREAD_PRIORITY_ABOVE_NORMAL
(1)THREAD_PRIORITY_HIGHEST
(2)THREAD_PRIORITY_TIME_CRITICAL
(15)