本次学习 线程传值问题
相信大家都想到过线程函数应该和一般的函数一样,可以传递值吧
这次就来学习线程传值
其实创建线程函数里面就有一个参数用来传值的
HANDLE CreateThread (
SEC_ATTRS SecurityAttributes,
ULONG StackSize,
SEC_THREAD_START StartFunction,
PVOID ThreadParameter, //用于传值的参数
ULONG CreationFlags,
PULONG ThreadId);
这次我们就来学习传值的问题吧
和上次一样 建立一个thread2_1的对话框
还是在thread2_1Dlg.h 头文件里面
加入
记住还是要讲 函数申明在类的 外面
然后给函数添加两个 私有的变量(创建线程时候需要用到的)
之后添加两个BUTTON按钮IDC_START 和IDC_STOP
添加下面代码
void CThread2_1Dlg::OnStart()
{
// TODO: Add your control notification handler code here
int n = 10 ;
hthread = CreateThread(
NULL , 0 , (LPTHREAD_START_ROUTINE)func , (void *)n , 0 , &threadid
);
( (CButton*)GetDlgItem(IDC_START))->EnableWindow(false);
( (CButton*)GetDlgItem(IDC_BSTOP))->EnableWindow(true);
}
void CThread2_1Dlg::OnBstop()
{
// TODO: Add your control notification handler code here
m_brun = false ;
( (CButton*)GetDlgItem(IDC_START))->EnableWindow(true);
( (CButton*)GetDlgItem(IDC_BSTOP))->EnableWindow(false);
}
然后在 thread2_1.cpp文件里面 添加
bool m_brun;
最后写
线程函数
void func(int m) //线程函数
{
CString ss;
while (m_brun)
{
m++;
ss.Format( "%d" , m );
::SetDlgItemText( AfxGetMainWnd()->m_hWnd , IDC_DISPLAY , ss );
Sleep(1000);
}
}
最后编译连接就可以运行了
可能大家会问为什么需要这样
其实 我们在类外面定义一个同样的 int型数据就行了
为什么还需要这么麻烦?
可是我们定义的是结构体呢 ?
是不是很占用内存?
大家仔细想想就明白了 。
对了 还有一个问题就是在用vc2010写 线程函数的时候 可能会出现问题
可以把
::SetDlgItemText( AfxGetMainWnd()->m_hWnd , IDC_DISPLAY , ss );
改为
::SetDlgItemText( AfxGetApp()->m_pMainWnd->m_hWnd , IDC_DISPLAY , ss );
就可以了 。
代码下载地址
http://download.youkuaiyun.com/detail/midle110/4410325