一、如何安全的結(jié)束你的線程
在你的線程中設(shè)立一個標志,利用其值要求線程結(jié)束自己. 我們不是要寫一個 busy loop 來檢驗標志值,我們使用一個手動設(shè)置的 event 對象。Wroker 線程可以檢查 event 對象的狀態(tài)或是等待它,視情況而定。
主線程代碼:
--------------------------------------
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;
}
}
二、調(diào)整線程優(yōu)先權(quán)
BOOL SetThreadPriority(HANDLE hThread, int nPriority);
hThread - 代表線程
nPriority - 優(yōu)先權(quán)層級數(shù)
TRUE - 成功; FALSE - 失敗
可用下面函數(shù)獲得線程優(yōu)先權(quán)層級數(shù):
int GetThreadPriority(HANDLE hThread);
三、創(chuàng)建線程時指定優(yōu)先權(quán)
HANDLE hThread;
DWORD thrdId;
hThread = CreateThread(NULL,
0,
ThreadFunc,
0,
CREATE_SUSPEND,
&thrdId)
SetThreadPriority(thrdId, THREAD_PRIORITY_IDLE);
一旦線程設(shè)置妥當,可調(diào)用下面函數(shù)執(zhí)行:
DWORD ResumeThread(HANDLE hThread);
該函數(shù)失敗時返回 0xFFFFFFFF