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;
}
相关推荐
Dxy123931021611 分钟前
ECharts折线图入门学习:从基础到实战的完整指南
学习·信息可视化·echarts
_Twink1e19 分钟前
[算法竞赛]九、C++标准模板库STL常用容器大全
开发语言·c++
_李小白32 分钟前
【OSG学习笔记】Day 25: OSG 设计架构解析
笔记·学习·架构
风中的小熊生气38 分钟前
MQ 学习笔记
笔记·学习
bu_shuo1 小时前
c++中对数组求和
开发语言·c++
elseif1231 小时前
【Markdown】指南(上)
linux·开发语言·前端·javascript·c++·笔记
solicitous1 小时前
之前说到收到一个口头机遇,续集来了
学习·生活
星辰徐哥1 小时前
C++网络编程:TCP服务器与客户端的实现
网络·c++·tcp/ip
猿类崛起@1 小时前
CherryStudio配置本地MCP服务器实现FileSystem本地文件系统读写操作
人工智能·学习·程序员·大模型·agent·ai大模型·mcp
·心猿意码·1 小时前
C++ volatile 与 std::atomic 底层语义剖析
c++