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;
}
相关推荐
qq_571099358 分钟前
学习周报四十八
学习
MartinYeung510 分钟前
[论文学习]大型语言模型中个人可识别资讯(PII)的机器遗忘技术:UnlearnPII 基准与 PERMU 方法的分析
人工智能·学习·语言模型
纪念 22920 分钟前
【无标题】
学习
xian_wwq24 分钟前
【学习笔记】「大模型安全:攻击面演化史」第 01 篇 Prompt Injection
笔记·学习·prompt
晚风吹红霞44 分钟前
深入浅出 STL 之 map 与 set:从入门到实战
开发语言·c++
牛油果子哥q1 小时前
【C++封装】C++封装思想与访问权限终极精讲:public/private/protected权限解析、类封装设计、继承权限变化、工程私有化规范与面试坑点
c++·面试
织梦旅途1 小时前
C++ 第一课 从 Hello Word!立刻开始
c++
.千余1 小时前
【C++】 String 常用操作:增删查改 | 查找 | 截取 | IO
java·服务器·开发语言·c++·笔记·学习
xian_wwq1 小时前
【学习笔记】「大模型安全:攻击面演化史」第 04 篇-模型窃取与供应链安全
笔记·学习·ai安全
十月的皮皮1 小时前
C语言学习笔记20260607-判断一个数是否为2的n次方(三种方法)
c语言·笔记·学习