我正在使用Windows线程在C中做一个游戏,但是在游戏的某个时刻我需要在特定时刻停止一些线程,我不知道停止线程所需的函数和参数,也不知道什么它返回。
这两个函数是相同的,一个简单的计时器,运行直到计数器达到限制,我想随时停止第二个线程,而不使用 WaitForSingleObject(hThread, Milliseconds) 的第二个参数。
DWORD WINAPI timer(LPVOID segundo)
{
int counter = 0;
while(counter<segundo)
{
counter++;
gotoxy(30,5);
printf("%d", counter);
Sleep(1000);
}
return NULL;
}
DWORD WINAPI prueba(LPVOID segundo)
{
int counter = 0;
while(counter<segundo)
{
counter++;
gotoxy(30,10);
printf("%d", counter);
Sleep(1000);
}
return NULL;
}
int main()
{
int limit = 5, *ptr;
*ptr = limit;
HANDLE hThread1, hThread2;
DWORD time, probo;
hThread1 = CreateThread(NULL, 0, timer, *ptr, 0, &time);
hThread2 = CreateThread(NULL, 0, prueba, *ptr, 0, &probo);
WaitForSingleObject(hThread2, INFINITE);
WaitForSingleObject(hThread1,INFINITE);
return 0;
}
最佳答案
使用 CreateEvent(NULL,FALSE,FALSE,NULL) 函数创建一个事件,将此事件句柄传递给线程,然后在线程过程中使用 WaitForSingleObject(hEvent,1000)
相反。每当你想停止线程时,调用SetEvent(hEvent)
,然后在线程过程中执行:
DWORD retval = WaitForSingleObject(hEvent,1000);
if( retval != WAIT_TIMEOUT )
return 0;
关于c - 如何在 Windows 中结束线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8466996/