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 小时前
C++ STL篇 红黑树的模拟实现
开发语言·c++
研究点啥好呢10 小时前
Momenta后端开发面试题精选:10道高频考题+答案解析(数据产线方向)
c++·python·面试·求职招聘
Hical6110 小时前
C++26 前瞻心得:下一代 C++ 最值得期待的特性
c++
悲伤小伞10 小时前
Linux_传输层协议TCP详解
linux·网络·c++·网络协议·tcp/ip
谙弆悕博士10 小时前
Python快速学习——第5章:集合
python·学习
Frank_refuel11 小时前
C++之STL->string类的使用和实现
java·开发语言·c++
fpcc11 小时前
跟我学C++中级篇—Linux文件读写的分析
linux·c++
南境十里·墨染春水11 小时前
linux学习进展 C语言连接mysql
linux·c语言·学习
郝学胜-神的一滴11 小时前
干货版《算法导论》03:动态数组 × 链表的极致平衡艺术
java·数据结构·c++·python·算法·链表
li星野11 小时前
栈与队列通关八题:从括号匹配到接雨水,手撕LeetCode高频题(Python + C++)
c++·python·leetcode