欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

windows API(8)线程控制

程序员文章站 2022-03-05 09:54:05
...

线程控制

如何让线程停下来
  1. 线程让自己停下来,Sleep函数
  2. 线程让别的线程停下来,SuspendThread函数
  3. 线程让别的线程恢复,ResumeThread()函数

注意,线程是可以挂起多次的,必须调用同样次数的恢复线程函数才可以让线程恢复

等待线程结束
  1. WaitForSingleObject()函数,等待上一个线程执行结束后,再接着执行
int main()
{
    HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, NULL, NULL);
    
    //在线程执行完毕后,才会接着执行下面的内容
    WaitForSingleObject(hThread, INFINITE);
    
    printf("线程执行完毕\n");
    CloseHandle(hThread);
    return 0;
}
  1. 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;
}
  1. 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;
}
相关标签: windows API