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;
}
相关推荐
泡泡鱼(敲代码中)1 小时前
MySQL基础学习笔记:从数据模型到DDL全掌握
开发语言·数据库·笔记·学习·mysql
老赵的博客2 小时前
c++面试之从虚函数表到Rtti一次性讲清楚
c++·qt
fanged2 小时前
Agent的Skills(TODO)
学习
是隼人3 小时前
buuctf-pwn picoctf_2018_shellcode(ret2shellcode)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
m4Rk_3 小时前
【论文阅读】Agent 记忆机制(69):STITCH——用上下文意图解决“语义相关但情境错误”的记忆检索
论文阅读·人工智能·学习·开源·github
2601_949950633 小时前
个人在线刷题的工具
学习·考研·小程序·刷题·小程序推荐
傲世仙尊3 小时前
System V 进程间通信详解:共享内存、消息队列与信号量(CSDN博客)
linux·开发语言·c++
一尘之中3 小时前
深入解析面向服务的架构(SOA):从特性到实施
学习·架构·ai写作
cvby4 小时前
C++11
开发语言·c++
6Hzlia4 小时前
【Classic 150 刷题计划】 LeetCode 26. 删除有序数组中的重复项 | C++ 快慢双指针经典模板
c++·算法·leetcode