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;
}
相关推荐
浔溺5 小时前
al+大数据每日学习笔记26
笔记·学习
xx~t5 小时前
嵌入式——进程与线程1
linux·c语言·学习·嵌入式·进程与线程
老当益壮梁奶奶6 小时前
Linux软件编程学习笔记(七):线程分离与线程间通信详解
linux·c语言·c++·笔记·学习
我命由我123457 小时前
UI 设计 7 种排列方式
xml·学习·ui·html·产品运营·产品经理·学习方法
常驻客栈7 小时前
B-深入理解计算机系统第3版之第8章:异常控制流
笔记·学习·常驻客栈·深入理解计算机系统·学习笔记‘’
lzhdim8 小时前
13、JavaScript事件循环机制 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
小杨不想秃头8 小时前
信息安全工程师考试
学习·网络安全
喜欢吃豆8 小时前
otes on LLMs 更新:一份更系统的大模型工程学习手册
学习·大模型·agent
AOwhisky8 小时前
Linux 网络服务架设学习笔记(第五期)——Web 服务(上篇):Apache HTTP Server——从静态到动态
linux·运维·服务器·笔记·学习·云计算·apache
绘梨衣5479 小时前
异步任务队列-学习2
爬虫·python·学习·任务队列