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;
}
相关推荐
Skrrapper5 分钟前
【编程史】微软的起家之路:一代传奇的诞生
数据库·c++·microsoft
点亮一颗LED(从入门到放弃)12 分钟前
C语言学习笔记
笔记·学习
找了一圈尾巴31 分钟前
Python 学习-深入理解 Python 进程、线程与协程(下)
开发语言·python·学习
Super小白&33 分钟前
C++ 高可用线程池实现:核心 / 非核心线程动态扩缩容 + 任务超时监控
c++·线程池
活跃的煤矿打工人1 小时前
【星海随笔】标准学习
学习
多多想1 小时前
C++扫盲——为什么C/C++分文件要写h和cpp?
c语言·c++
liulilittle1 小时前
C++判断wchar_t空白字符
开发语言·c++
晨非辰1 小时前
算法闯关日记 Episode :解锁链表「环形」迷局与「相交」奥秘
数据结构·c++·人工智能·后端·python·深度学习·神经网络
今天你TLE了吗2 小时前
通过RocketMQ延时消息实现优惠券等业务MySQL当中定时自动过期
java·spring boot·后端·学习·rocketmq
烤麻辣烫2 小时前
黑马程序员苍穹外卖(新手)DAY12
java·开发语言·学习·spring·intellij-idea