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;
}
相关推荐
牛肉在哪里3 分钟前
ros2 从零开始28 监听广播C++
开发语言·c++·算法·机器人
玖玥拾4 分钟前
C/C++ 数据结构(二)双向链表
c语言·数据结构·c++
chase。5 分钟前
【学习笔记】Unified World Models:基于视频-动作耦合扩散的机器人预训练新范式
笔记·学习·音视频
枕星而眠18 分钟前
Linux守护进程完全指南:从原理到实战
linux·运维·服务器·c++·后端
QiLinkOS21 分钟前
极客精神与商业思维的融合实践(2)
c语言·c++·人工智能·算法·开源协议
charlie11451419124 分钟前
现代C++特性指南——constexpr 构造函数与字面类型
开发语言·c++
一锅炖出任易仙30 分钟前
创梦汤锅学习日记day32
学习·ai·游戏引擎
影寂ldy1 小时前
C# 事件完整学习笔记(发布订阅 + 自定义事件 + 内置 EventHandler)
笔记·学习·c#
极客BIM工作室1 小时前
OCCT gp_Trsf 三维变换类深度剖析:经典设计与底层陷阱
c++
醉城夜风~1 小时前
类和对象III
开发语言·c++