add(ncount);
}
::postmessage(
(hwnd)pparam,
wm_threadfinished,//用户自定义消息
0,0);
return 0;
}
编写onstart函数:
void cthreaddlg::onstart()
{
m_ntimer=settimer(1,100,null);//0.1秒
assert(m_ntimer!=0);
getdlgitem(idc_start)->enablewindow(false);
afxbeginthread(threadproc,getsafehwnd(),thread_proirity_nomal);
}
编辑oncancel函数如下:
void cthreaddlg::oncancel()
{
if(ncount==0)
cdialog::oncancel();
else ncount=500;
}
处理onthreadfinished函数
hresult cthreaddlg::onthreadfinished(wparam wparam,lparam lparam)
{
cdialog::onok();
return 0;
}
3.用事件使线程同步:
利用waitforsingleobject函数
在stdafx.h中写入下面一行
#include <afxmt.h>//由于使用了事件
声明两个全局变量
cevent m_start,m_kill;
在初始化函数中启动线程;
重新编写onstart函数:
void cthreaddlg::onstart()
{
m_ntimer=settimer(1,100,null);//0.1秒
assert(m_ntimer!=0);
getdlgitem(idc_start)->enablewindow(false);
m_start.setevent();
}
重新编辑oncancel函数如下:
void cthreaddlg::oncancel()
{
if(ncount==0)
m_start.setevent();
else m_kill.setevent();
}
编写全局函数如下:
uint threadproc(lpvoid pparam)
{
::waitforsingleobject(m_start,infinite);
while(ncount<500)
{
add(ncount);
if(::waitforsingleobject(m_start,0)=wait_object_0)
break;
}
::postmessage(
(hwnd)pparam,