#include <process.h> #include <windows.h> #include <iostream> using namespace std; //WaitForSingleObject 检测对象是否有信号。可以配合event使用,或直接检测对象。 //如果Object被激活了,或者正在使用,那么该Object就是无信号,也就是不可用;另一方面,如果Object可用了,那么它就恢复有信号了 //如果要检测正在使用,那么等待时间为0就好。会返回WAIT_TIMEOUT。 //如果要检测是否停止,那么稍微加点时间。会返回WAIT_OBJECT_0
//1.线程 正常返回.
//2.等待一点点时间.
//3.WaitForSingleObject只有返回obj,说明成功.
//4.那么就关闭handle,并设置handle为null.
bool runing=true; HANDLE m_hThreadHandle = NULL; unsigned __stdcall ThreadFunction(LPVOID pThreadData) { while(runing) { Sleep(500); cout<<"running"<<endl; } return 0; } unsigned __stdcall CheckThreadFunction(LPVOID pThreadData) { while(true) { Sleep(1000); DWORD dw = WaitForSingleObject(m_hThreadHandle, 10); if (dw==WAIT_TIMEOUT) { cout<<"wait"<<endl; } else if(dw==WAIT_OBJECT_0) { cout<<"obj"<<endl; } else if(WAIT_FAILED==dw) { cout<<"fall"<<dw<<endl; } else { cout<<"other:"<<dw<<endl; } } return 0; } //检测线程是否在运行。 int main() { //LSU_HELPER::CThread mythread(myloop); //mythread.StartThread(); //Sleep(5000); //mythread.StopThread(); //Sleep(1000);//等待线程退出, m_hThreadHandle=(HANDLE)_beginthreadex(NULL,0,ThreadFunction,NULL,0,NULL);// HANDLE m_hThreadHandlecc=NULL; m_hThreadHandlecc=(HANDLE)_beginthreadex(NULL,0,CheckThreadFunction,NULL,0,NULL);// Sleep(5000); runing=false; Sleep(5000); return 0; }