方法一:正常创建线程函数,如果要在线程函数中调用对话框类中的变量,则需要对话框的类指针传递给线程函数:在类外定义CWnd *m_Cwnd;在类中赋值 m_Cwnd = this;然后在线程函数中使用m_Cwnd ;
代码如下:
unsigned int __stdcall Thread1Function(void *pPM)//线程1实现函数
{
int nNum = 0;
while (true)
{
CString strThread1;
strThread1.Format(_T("线程1开启 %d s"), nNum);
m_Cwnd->GetDlgItem(IDC_STATIC_THREAD1)->SetWindowTextW(strThread1);
Sleep(1000);
nNum++;
}
return true;
}
void CCreateThread2functionsDlg::OnBnClickedButtonThread1()//“线程1开启”按钮开启响应函数
{
UINT threadId;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, Thread1Function, 0, 0, &threadId);
//用第一种方法创建线程,如果要在线程函数中调用对话框类中的变量,则需要对话框的类指针传递给线程函数:
//在类外定义CWnd *m_Cwnd;在类中赋值 m_Cwnd = this;
//如果是在win32应用程序中写该行代码选择需要#include <process.h>
if (hThread == NULL)
{
cout << "Starting Thread1 Failed!" << endl;
}
}
方法二:通过使用联合,将线程函数变成类函数,从而省去通过类指针访问类变量这个麻烦
代码如下:
在类的.h文件中定义:
private:
union _Proc
{
unsigned(_stdcall * ThreadProc)(void*);
unsigned(_stdcall CCreateThread2functionsDlg::*MemProc)();
} ProcThread2;
unsigned int __stdcall CCreateThread2functionsDlg::Thread2Function();
在类的.cpp文件中:
unsigned int CCreateThread2functionsDlg::Thread2Function()
{
int nNum = 0;
while (true)
{
CString strThread1;
strThread1.Format(_T("线程2开启 %d s"), nNum);
m_Cwnd->GetDlgItem(IDC_STATIC_THREAD2)->SetWindowTextW(strThread1);
Sleep(1000);
nNum++;
}
return 0;
}
void CCreateThread2functionsDlg::OnBnClickedButtonThread2()//“线程2开启”按钮开启响应函数
{
ProcThread2.MemProc = &CCreateThread2functionsDlg::Thread2Function;
UINT threadId;
HANDLE hThread2 = (HANDLE)_beginthreadex(NULL, 0, ProcThread2.ThreadProc, (LPVOID)this, 0, &threadId);
//用第二种方法创建线程,如果要在线程函数中调用对话框类中的变量,可直接访问,不需要对话框的类指针传递给线程函数!
//如果线程函数中用到大量对话框中的类变量的话,可用这种方法少写很多代码。
if (hThread2 == NULL)
{
cout << "Starting Thread2 Failed!" << endl;
}
}
运行结果: