返回> 网站首页 

线程的退出

yoours2011-08-05 11:07:01 阅读 1294

简介一边听听音乐,一边写写文章。

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;
}


微信小程序扫码登陆

文章评论

1294人参与,0条评论