一个看似简单却迷惑的问题。
各位,我编写了个测试while循环的小程序,代码如下
//只是一个简单fix, 自己改进
bool shutdown = false;
unsigned int __stdcall ThreadFun(PVOID pM)
{
int i=1;
while (!shutdown && i<10000)
{
i=i+1;
Sleep(100);
}
AfxMessageBox("执行完毕");
return 0;
}
void CTest_WhileDlg::OnButton1()
{
HANDLE handle=(HANDLE)_beginthreadex(NULL,0,ThreadFun,NULL,0,NULL);
CloseHandle(handle); //不要等待,也不要循环,只是简单的调度一下
}
//新加一个按钮,在关闭程序前, 关闭子线程
void CTest_WhileDlg::OnButton2()
{
shutdown = true;
}
void CTest_WhileDlg::OnButton1()
{
// TODO: Add your control notification handler code here
int i=1;
MSG msg;
while (i<10000)
{
i=i+1;
Sleep(100);
if (0==i%10)
if (GetMessage(&msg,NULL,0,0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}