C++类内多线程创建和调用成员变量的两种方式

std::thread的构造函数的参数不能是非静态成员函数,需要静态成员函数,如果想要在类内创建线程并调用类对象的成员变量,需要做一些处理,实现方式如下:

第一种:

类的对象作为线程的静态成员函数传入类指针使用,在类里调用

#include <iostream> 
#include <thread>
#include <unistd.h>

using namespace std;

class MyTest
{
public:
	void run();
	static void func_work(MyTest*);

private:
	int n = 0;
};


void MyTest::work(MyTest* ptr)
{
	while (1)
	{
		cout << (ptr->n)++ << endl;
		sleep(2);
	}
}

void MyTest::run()
{
	std::thread my_thread(func_work, this);
	my_thread.detach();
}

int main()
{
	MyTest* test = new MyTest;
	test->run();

	while (1);
	return 0;
}

第二种:

不必把线程函数定义为静态函数,直接用std::bind函数把函数和this指针绑定

#include <iostream> 
#include <thread>
#include <unistd.h>

using namespace std;

class MyTest
{
public:
	void run();
	void func_work();

private:
	int n = 0;
};


void MyTest::func_work()
{
	while (1)
	{
		cout << n++ << endl;
		sleep(2);
	}
}

void MyTest::run()
{
    //std::thread my_thread(std::bind(std::mem_fn(&MyTest::func_work), this));
	std::thread my_thread(std::bind(&MyTest::func_work, this));
	my_thread.detach();
}

int main()
{
	MyTest* test = new MyTest;
	test->run();

	while (1);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值