线程控制
如何让线程停下来
- 线程让自己停下来,Sleep函数
- 线程让别的线程停下来,SuspendThread函数
- 线程让别的线程恢复,ResumeThread()函数
注意,线程是可以挂起多次的,必须调用同样次数的恢复线程函数才可以让线程恢复
等待线程结束
- WaitForSingleObject()函数,等待上一个线程执行结束后,再接着执行
int main()
{
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, NULL, NULL);
//在线程执行完毕后,才会接着执行下面的内容
WaitForSingleObject(hThread, INFINITE);
printf("线程执行完毕\n");
CloseHandle(hThread);
return 0;
}
- WaitForMultipleObjects()函数
int main()
{
HANDLE harrThread[2];
harrThread[0] = CreateThread(NULL, 0, ThreadProc, NULL, NULL, NULL);
harrThread[1] = CreateThread(NULL, 0, ThreadProc, NULL, NULL, NULL);
//在线程全部执行完毕后,才会接着执行下面的内容
WaitForMultipleObjects(2, harrThread, TRUE, INFINITE);
printf("线程执行完毕\n");
CloseHandle(harrThread[0]);
CloseHandle(harrThread[1]);
return 0;
}
- GetExitCodeThread()函数
获取线程的返回结果
int main()
{
HANDLE harrThread[2];
DWORD dwResult1;
DWORD dwResult2;
harrThread[0] = CreateThread(NULL, 0, ThreadProc, NULL, NULL, NULL);
harrThread[1] = CreateThread(NULL, 0, ThreadProc, NULL, NULL, NULL);
//在线程全部执行完毕后,才会接着执行下面的内容
WaitForMultipleObjects(2, harrThread, TRUE, INFINITE);
//dwResult1和dwResult2表示返回值
GetExitCodeThread(harrThread[0], &dwResult1);
GetExitCodeThread(harrThread[1], &dwResult2);
printf("线程执行完毕\n");
CloseHandle(harrThread[0]);
CloseHandle(harrThread[1]);
return 0;
}