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;
}
相关推荐
MartinYeung532 分钟前
[论文学习]针对 LLM 的间接提示注入攻击用于高效隐私洩露之深度分析
人工智能·学习
字节高级特工1 小时前
智能指针原理与使用场景全解析
开发语言·c++·算法
AI棒棒牛1 小时前
YOLO26 全网独家改进创新: MIT 2025 振荡状态空间模型:引入可学习的阻尼机制,独家创新!
人工智能·学习·目标检测·计算机视觉·yolo26
留白_1 小时前
pandas进阶学习
学习·pandas
插件开发1 小时前
CUDA11-VS2015安装-工具链测试-Helloworld程序
c++·gpu·cuda
_Evan_Yao1 小时前
递归函数入门:以阶乘和斐波那契数列为例
python·学习·算法
攻城狮Soar1 小时前
STL源码解析之deque
开发语言·c++
AI_零食2 小时前
HarmonyOS ArkTS 设计系统构建实战指南
学习·华为·harmonyos·鸿蒙·鸿蒙系统
数智工坊2 小时前
周志华《Machine Learning》学习笔记--第十五章--规则学习
笔记·学习·机器学习
brevity_souls2 小时前
信息安全与网络安全的区别及其学习内容
网络·学习·web安全