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;
}
相关推荐
遇印记10 小时前
传输层,网络层
运维·服务器·网络·windows·学习
clorinda11 小时前
PyQt5学习:从界面搭建到与机器学习实战
学习
WL学习笔记12 小时前
C & C++ 内存管理
c++·c++内存管理
欣欣之王来了13 小时前
Vue3项目脚手架:Vite vs Vue CLI怎么选?
前端·学习·架构·项目·vue3教程
kaixin_啊啊13 小时前
【零基础学AI】第 7 章——让 AI 辅助学习和办公
人工智能·学习
信奥卷王13 小时前
[GESP202506 六级] 学习小组(含视频)
学习
宛 禾14 小时前
Qt 控件入门:QLabel 从拖拽到对象树,一篇讲透
c++·qt·学习
hetao173383714 小时前
联盟场-提高组-R7 & ZYZSC-S-Round 11
c++·算法
程序喵大人14 小时前
【C++入门】编译链接模型 - 07 链接器怎样把符号对上号
开发语言·c++·编译器·编译链接·链接器
无敌贵点大王14 小时前
嵌入式软件面试经(自用)
c语言·stm32·单片机·学习·mongodb·面试·职场和发展