Thread Manipulation
Suspend and Resume
Windows provides SuspendThread
and ResumeThread
APIs to temporarily pause and continue a thread's execution.
#include <windows.h>
DWORD WINAPI ThreadFunc(LPVOID lpParam) {
for (int i = 0; i < 10; ++i) {
Sleep(500);
printf("Count: %d\n", i);
}
return 0;
}
int main() {
HANDLE hThread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
Sleep(2000);
SuspendThread(hThread);
printf("Thread suspended.\n");
Sleep(2000);
ResumeThread(hThread);
printf("Thread resumed.\n");
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
Setting Thread Priority
Adjust a thread's priority using SetThreadPriority
and retrieve current priority with GetThreadPriority
.
Priority Constant | Description |
---|---|
THREAD_PRIORITY_LOWEST | Lowest possible priority. |
THREAD_PRIORITY_BELOW_NORMAL | Below normal priority. |
THREAD_PRIORITY_NORMAL | Default priority. |
THREAD_PRIORITY_ABOVE_NORMAL | Above normal priority. |
THREAD_PRIORITY_HIGHEST | Highest possible priority. |
#include <windows.h>
HANDLE hThread = CreateThread(NULL, 0, SomeFunc, NULL, 0, NULL);
if (hThread) {
SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);
DWORD prio = GetThreadPriority(hThread);
printf("Current priority: %lu\n", prio);
CloseHandle(hThread);
}
Thread Affinity
Control the processor(s) a thread can run on using SetThreadAffinityMask
.
#include <windows.h>
DWORD WINAPI Work(LPVOID) {
for (;;) {
// intensive work
}
return 0;
}
int main() {
HANDLE h = CreateThread(NULL, 0, Work, NULL, 0, NULL);
// Restrict to CPU 0
SetThreadAffinityMask(h, 0x1);
WaitForSingleObject(h, INFINITE);
CloseHandle(h);
return 0;
}
Forceful Termination (Deprecated)
While TerminateThread
can abruptly end a thread, it is discouraged due to resource leaks. Use cooperative cancellation instead.
#include <windows.h>
void StopThread(HANDLE hThread) {
// Not recommended
TerminateThread(hThread, 0);
}