返回> 网站首页
线程的退出
yoours2011-08-05 11:07:01
简介一边听听音乐,一边写写文章。
1. 使用信号量
bool DoTask(HANDLE hQuitSignal)
{
while (!QuitCondition)
{
if (WaitForSingleObject(hQuitSignal, 0) == WAIT_OBJECT_0)
{
return false;
}
// Do something
}
return true;
}
2. 强制,未测试
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
DWORD CALLBACK infinite(void* arg) { for (;;) Sleep(0); return 0; }
void cancel(void) { ExitThread(12); }
int main(void)
{
DWORD tid = 0;
HANDLE thread = CreateThread(NULL, 0, infinite, 0, 0, &tid);
CONTEXT ctx = {0};
ctx.ContextFlags = CONTEXT_ALL;
SuspendThread(thread);
GetThreadContext(thread, &ctx);
ctx.Eip = (DWORD)cancel;
SetThreadContext(thread, &ctx);
ResumeThread(thread);
WaitForSingleObject(thread, INFINITE);
GetExitCodeThread(thread, &tid);
CloseHandle(thread);
return (int)tid;
}