c++中两种创建线程的方法

方法一:正常创建线程函数,如果要在线程函数中调用对话框类中的变量,则需要对话框的类指针传递给线程函数:在类外定义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;
	}
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GreenHandBruce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值