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;
}
相关推荐
洁洁!4 分钟前
手搓 C++ 线程池详细讲解以及如何面试应答
java·c++·面试
坤坤子吖25 分钟前
C++继承:继承的基本用法与访问规则
开发语言·c++·笔记·学习
Demon--hx35 分钟前
C++ 文件流:理解 ifstream/ofstream 与 RAII 机制
开发语言·c++
纪念 22937 分钟前
C++ stack和queue
开发语言·c++
CodeYp20191 小时前
第6讲:模板初阶
开发语言·c++·模板
.YM.Z1 小时前
【C++11】初识——右值引用和移动语义,可变参数模板
c++·c++11
代码山河1 小时前
键盘输入与输出:Scanner与System.out详解
java·学习·架构·教程·面向对象·项目
一楼的猫1 小时前
活动会议照片直播云相册:服务形式与适用场景
学习
愤怒火龙果1 小时前
AIGC 安全学习笔记02 后门攻击・LLM 安全靶场・提示词注入
学习·安全·aigc
要练八块腹肌1 小时前
红黑树的实现以及对map和set的封装
c++