C++线程安全退出

HANDLE m_EvtThreadExit[MaxVisionNum];   //定义

方法一

for(int i=0;i<MaxVisionNum;i++)

  m_EvtThreadExit[index] = CreateEvent(NULL,false,false,NULL);  //手动创建

//线程函数

UINT CMilTestDlg::VisionThread(LPVOID param)
{
TThreadParam * pParam = (TThreadParam *)param;
CMilTestDlg * pDlg = (CMilTestDlg *)(pParam->pThis);
int visionIndex = pParam->visionIndex;
pDlg->VisionProcess(visionIndex);

SetEvent(m_EvtThreadExit[index]);    //线程函数最后,设置事件
return 1;
}



方法二

for (int i=0;i<MaxVisionNum;i++)
{
threadParma[i].pThis = this;
threadParma[i].visionIndex = i;
CWinThread *pthread = AfxBeginThread( VisionThread, &(threadParma[i]), THREAD_PRIORITY_NORMAL, 0, 
CREATE_SUSPENDED );
 pthread->m_bAutoDelete = false;             ////关闭句柄自动删除
 m_EvtThreadExit[i] = pthread->m_hThread;        //关联CWinThread句柄
pthread->ResumeThread();

}



方法三

for (int i=0;i<MaxVisionNum;i++)
{
threadParma[i].pThis = this;
threadParma[i].visionIndex = i;
m_EvtThreadExit[i] = CreateThread(NULL,0,ThreadProc,&(threadParma[i]),0,NULL);   //关联句柄
}

DWORD WINAPI ThreadProc(LPVOID lpParam) 
{ 
TThreadParam * pParam = (TThreadParam *)lpParam;
CMilTestDlg * pDlg = (CMilTestDlg *)(pParam->pThis);
int visionIndex = pParam->visionIndex;
pDlg->VisionProcess(visionIndex);
return 1;
}





/*****************************通用 **************************************/
//判断退出,

void CMilTestDlg::DoEvents()
{
MSG msg;
while (::PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);    
}
}

void CMilTestDlg::WaitAllThreadExit(DWORD time)
{
DWORD t=::GetTickCount();
while(::GetTickCount() -t < time)
{
DoEvents();                  //这个很关键,否则线程与UI相关时,会卡在里面
//线程同步的两个比较重要的函数为WaitForSingleObject()和WaitForMultipleObjects(),具体使用请参考MSDN。这两个函数都是阻塞函数,一直等待授信的对象发生才返回。
int ret = WaitForMultipleObjects(MaxVisionNum,m_EvtThreadExit,true,1); if(ret == WAIT_OBJECT_0) { break; } } TRACE("cost (ms): %d\n",GetTickCount() - t); }

 

posted on 2017-08-28 13:37  strangeman  阅读(1079)  评论(0编辑  收藏  举报

导航