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;
}
相关推荐
玩转单片机与嵌入式6 分钟前
玩转边缘AI(TInyML):需要掌握的C++知识汇总!
开发语言·c++·人工智能
历程里程碑22 分钟前
4 Git远程协作:从零开始,玩转仓库关联与代码同步(带实操代码讲解)
大数据·c++·git·elasticsearch·搜索引擎·gitee·github
汉克老师1 小时前
GESP5级C++考试语法知识(贪心算法(一)课堂例题精讲)
c++·贪心算法·gesp5级·gesp五级·贪心规律
墨染千千秋1 小时前
C++头文件的使用,和各个头文件与头文件用处
c++
呱呱巨基1 小时前
Linux 基础IO
linux·c++·笔记·学习
旖-旎1 小时前
深搜练习(N皇后)(10)
c++·算法·深度优先·力扣
头发够用的程序员2 小时前
C++和Python面试经典算法汇总(一)
开发语言·c++·python·算法·容器·面试
水龙吟啸3 小时前
数据结构与算法随机复习–Day1
数据结构·c++·算法
萑澈3 小时前
智能增强与范式演进:OpenClaw 与 Hermes Agent 自我学习机制深度研究报告
学习
十五年专注C++开发3 小时前
浅谈LLVM
开发语言·c++·qt·clang·llvm