C++多线程学习[三]:成员函数作为线程入口

一、成员函数作为线程入口

cpp 复制代码
#include<iostream>
#include<thread>
#include<string>

using namespace std;

class Mythread
{
public:
	string str;
	void Test()
	{
		cout << str << endl;
	}
};
int main()
{
	Mythread test;
	test.str = "Test";
	thread t = thread(&Mythread::Test, &test);
	t.join();
	return 0;
}

二、简单的线程封装

cpp 复制代码
#include<iostream>
#include<thread>
#include<string>

using namespace std;

class Mythread
{
public:
	void Start()
	{
		is_exit_ = false;
		th_ = thread(&Mythread::Main,this);
	}
	void Wait()
	{
		if (th_.joinable())//检测线程是否已经结束
			th_.join();
	}
	void Stop()
	{
		is_exit_ = true;
		Wait(); 
	}
	bool is_exit() { return is_exit_; }
private:
	virtual void Main() = 0;
	thread th_;
	bool is_exit_ = false;
};

class M_thread : public Mythread
{
public:
	void Main() override
	{
		cout << "Thread is begin" << endl;
		while (!is_exit())
		{
			this_thread::sleep_for(1s);
			cout << "." << flush;
		}
	}
};
int main()
{
	M_thread th;
	th.Start();
	this_thread::sleep_for(10s);
	th.Stop();
	th.Wait();
	return 0;
}

三、lambda临时函数作为线程入口

cpp 复制代码
#include<iostream>
#include<thread>
#include<string>
using namespace std;
class Test
{
public:
	void Start()
	{
		thread th = thread([this]() {
			cout <<s << endl;
			});
		th.join();
	}
private:
	string s = "Test class`s lambda";
};

int main()
{
	thread th([]() {cout << "Test lambda" << endl; });
	th.join();
	Test t;
	t.Start();
	return 0;
}
相关推荐
0 0 04 小时前
CCF-CSP 39-2 水印检查(watermark)【C++】
c++·算法
plus4s4 小时前
2月15日(78,80,81题)
c++·算法·图论
瞎某某Blinder6 小时前
DFT学习记录[4] 电子和空穴的有效质量计算全流程
python·学习
zhangfeng11337 小时前
Warmup Scheduler深度学习训练中,在训练初期使用较低学习率进行预热(Warmup),然后再按照预定策略(如余弦退火、阶梯下降等)衰减学习率的方法
人工智能·深度学习·学习
zmzb01037 小时前
C++课后习题训练记录Day104
开发语言·c++
honiiiiii8 小时前
SMU winter week4
c++
zmzb01038 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
闻缺陷则喜何志丹8 小时前
【拆位法】P8743 [蓝桥杯 2021 省 A] 异或数列|普及+
c++·蓝桥杯·位运算·拆位法
fpcc9 小时前
跟我学C++中级篇——Concepts的循环依赖
c++·模板和元编程
red_redemption9 小时前
自由学习记录(118)
学习