2024年4月12日发(作者:)
terminatethread 例子
terminatethread是一个函数,可以强制终止一个线程的执行。
下面是一个 terminatethread 的例子:
#include
#include
using namespace std;
DWORD WINAPI ThreadFunc(LPVOID lpParam)
{
while (true)
{
cout << 'Thread is running.' << endl;
Sleep(1000);
}
return 0;
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, ThreadFunc, NULL,
0, NULL);
if (hThread == NULL)
{
cout << 'Error creating thread.' << endl;
- 1 -
return 1;
}
Sleep(5000); // 等待 5 秒钟
if (!TerminateThread(hThread, 0))
{
cout << 'Error terminating thread.' << endl;
return 1;
}
CloseHandle(hThread); // 关闭线程句柄
cout << 'Thread terminated.' << endl;
return 0;
}
上面的程序创建了一个新的线程,让它不停地输出一条消息。然
后等待 5 秒钟后,使用 terminatethread 函数强制终止该线程的执
行,并输出一条消息表示线程已经被终止。注意要关闭线程句柄。
- 2 -


发布评论