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;
}
相关推荐
啊董dong2 分钟前
noi-2025年12月23号作业
数据结构·c++·算法·noi
青岛少儿编程-王老师5 分钟前
CCF编程能力等级认证GESP—C++8级—20251227
java·开发语言·c++
幽络源小助理10 分钟前
SpringBoot+Vue智能学习平台系统源码 | 教育类JavaWeb项目免费下载 – 幽络源
vue.js·spring boot·学习
hd51cc12 分钟前
MFC打印技术
c++·mfc
爱吃生蚝的于勒26 分钟前
【Linux】零基础深入学习动静态库+深入学习地址
linux·运维·服务器·c语言·数据结构·c++·学习
_OP_CHEN37 分钟前
【从零开始的Qt开发指南】(十四)Qt 窗口之“三剑客”:工具栏、状态栏、浮动窗口进阶实战指南
开发语言·c++·qt·前端开发·gui开发·qt窗口
Noushiki40 分钟前
RabbitMQ 基础 学习笔记1
笔记·学习·rabbitmq
知识分享小能手41 分钟前
Ubuntu入门学习教程,从入门到精通, Ubuntu 22.04中的任务计划详解(16)
linux·学习·ubuntu
我命由我123451 小时前
Photoshop - Photoshop 工具栏(53)画板工具
笔记·学习·职场和发展·求职招聘·职场发展·学习方法·photoshop
郝学胜-神的一滴1 小时前
Qt重复添加控件问题探析:现象、原理与解决方案
开发语言·数据库·c++·qt·程序人生