一、如何安全的结束你的线程
在你的线程中设立一个标志,利用其值要求线程结束自己. 我们不是要写一个 busy loop 来检验标志值,我们使用一个手动设置的 event 对象。Wroker 线程可以检查 event 对象的状态或是等待它,视情况而定。
主线程代码:
--------------------------------------
HANDLE hThreads[2];
DWORD dwThreadID;
DWORD dwExitCode = 0;
hRequestExitEvent = CreateEvent(
NULL, /* Detault security */
TRUE, /* Manual reset */
FALSE, /* Non-active state */
NULL); /* Event name */
for (int i = 0; i < 2; ++i)
hThreads[i] = CreateThread(
NULL, /* Default security */
0, /* Default stack size */
ThreadFunc, /* Thread function address */
(LPVOID)i, /* Thread parameter */
0, /* Start when creating */
&dwThreadID);
Sleep(1000);
SetEvent(hRequestExitEvent);
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
for (i = 0; i < 2; ++i)
CloseHandle(hThreads[i]);
线程代码:
--------------------------------------
for (i = 0; i < 1000000; ++i)
{
// do something
if (WaitForSingleObject(hRequestExitEvent, 0) != WAIT_TIMEOUT)
{
printf("Received request to terminate\n");
return (DWORD) -1;
}
}
二、调整线程优先权
BOOL SetThreadPriority(HANDLE hThread, int nPriority);
hThread - 代表线程
nPriority - 优先权层级数
TRUE - 成功; FALSE - 失败
可用下面函数获得线程优先权层级数:
int GetThreadPriority(HANDLE hThread);
三、创建线程时指定优先权
HANDLE hThread;
DWORD thrdId;
hThread = CreateThread(NULL,
0,
ThreadFunc,
0,
CREATE_SUSPEND,
&thrdId)
SetThreadPriority(thrdId, THREAD_PRIORITY_IDLE);
一旦线程设置妥当,可调用下面函数执行:
DWORD ResumeThread(HANDLE hThread);
该函数失败时返回 0xFFFFFFFF