我做了以下追踪改动
[C++] syntaxhighlighter_viewsource syntaxhighlighter_copycode else if( WAIT_OBJECT_0 + 1)
{
while (PeekMessage(&msg,NULL,0,0,PM_NOREMOVE))
{
TRACE("收到消息,函数返回值为%d,进入消息分发 \n",result);
TRACE("message里面消息值 %d \n",msg.message);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
DEBUG里面调试信息是 :
[C++] syntaxhighlighter_viewsource syntaxhighlighter_copycode 收到消息,函数返回值为1,进入消息分发
message里面消息值 512
我在button1里面做了以下改动 能够正常运行了 但是MsgWaitForMultipleObjects任然不能正常工作,也就是不能收到线程退出的消息
[C++] syntaxhighlighter_viewsource syntaxhighlighter_copycode
BOOL CExample2Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
…
…
m_CANEvent=CreateEvent(NULL,FALSE,FALSE,NULL); //声明一个事件
runflag=0; //线程运行标志置0
return TRUE; // return TRUE unless you set the focus to a control
}
void CExample2Dlg::OnButton1() //用按钮开启线程的函数
{
// TODO: Add your control notification handler code here3
DWORD result ;
MSG msg ;
if(runflag==1) //如果线程正在运行
{
SetEvent(m_CANEvent); //发出让线程结束
TRACE("发送SetEvent信号,让线程结束 \n");
while (TRUE)
{
//wait for m_hThread to be over,and wait for
//QS_ALLINPUT(Any message is in the queue)
DWORD dwRet = MsgWaitForMultipleObjects (1, m_CANSendThreadHandle, FALSE, INFINITE, QS_ALLINPUT);
switch(dwRet)
{
case WAIT_OBJECT_0:
{
TRACE("MsgWaitForMultipleObjects 返回值 %ld ",dwRet);
TRACE("从WAIT_OBJECT_0消息退出while循环 \n");
}
break; //break the loop
case WAIT_OBJECT_0 + 1:
//get the message from Queue
//and dispatch it to specific window
{
TRACE("MsgWaitForMultipleObjects 返回值 %ld ",dwRet);
TRACE("说明返回WAIT_OBJECT_0 + 1 ,分发消息,继续while循环\n");
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
DispatchMessage(&msg);
}
continue;
default:
{
TRACE("MsgWaitForMultipleObjects 返回值 %ld ",dwRet);
TRACE("从default退出循环 \n");
}
break; // unexpected failure
}
break;
}
}
ResetEvent(m_CANEvent); //设置无信号,让线程进入等待超时的工作
uiButton=1; //标记这是按钮响应的函数启动的线程
pCANThreads=AfxBeginThread(MyThread1,this);
m_CANSendThreadHandle[0]=pCANThreads->m_hThread;
runflag=1;
Sleep(1000);
}
UINT CExample2Dlg::MyThread1(void *param)
{
TRACE("MyThread1 Begin\n");
CExample2Dlg *Dlg=(CExample2Dlg *)param;
int i;
CString tmp;
DWORD dw;
for(i=0;i<100000;i++)
{
dw = WaitForSingleObject(Dlg->m_CANEvent,10); //让其延迟10ms就输出一个数
if( dw == WAIT_OBJECT_0 ) //收到结束线程信号
{
Dlg->runflag=0; //线程运行标志复位
TRACE("MyThread1 End 1\n");
return 0; //退出
}
if( dw == WAIT_TIMEOUT) //延迟到了,就执行下面的显示数值
{
if(Dlg->uiButton == 1)
{
tmp.Format(" %d ",i);
Dlg->m_count.SetWindowText(tmp); //这个是让其在界面上面显示当前i的数值
}
if(Dlg->uiButton ==2 )
{
tmp.Format(" %d ",i);
Dlg->m_count2.SetWindowText(tmp); //这个是让其在界面上面显示当前i的数值
}
}
}
Dlg->runflag=0; //线程运行标志复位
TRACE("MyThread1 End\n");
return 0;
}
整个过程是这样的
第一次点button1: 线程开始,开始正常运行
第二次点button1: 因为执行SetEvent(m_CANEvent); 所以线程MyThread1结束 ,然后MsgWaitForMultipleObjects收到消息,(WAIT_OBJECT_0 + 1 ) 然后MsgWaitForMultipleObjects再次收到消息 ,是default消息 然后从default退出while循环 而非从(收到消息,WAIT_OBJECT_0)退出循环
然后再执行button1下面的开启线程操作,这个时候也能正常开启,因为实际上线程是退出了的,但是我就是纠结为什么MsgWaitForMultipleObjects等不到线程退出,它不能返回WAIT_OBJECT_0
下面是DEBUG回显的值
|