C++多线程学习[三]:成员函数作为线程入口

一、成员函数作为线程入口

#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;
}

二、简单的线程封装

#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临时函数作为线程入口

#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;
}

![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/f095c576c9a243a3a3c7639cc6fd6f92.png

相关推荐

  1. C++线之通过成员函数作为线入口

    2024-01-16 21:04:02       33 阅读
  2. C# 创建线函数

    2024-01-16 21:04:02       34 阅读
  3. C++ 线

    2024-01-16 21:04:02       26 阅读
  4. C++ 线

    2024-01-16 21:04:02       18 阅读
  5. C#线

    2024-01-16 21:04:02       12 阅读
  6. C++ 线

    2024-01-16 21:04:02       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-16 21:04:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-16 21:04:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-16 21:04:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-16 21:04:02       20 阅读

热门阅读

  1. Redis面试题14

    2024-01-16 21:04:02       30 阅读
  2. Nginx Ingress轻松上手 | Kubernetes服务管理指南

    2024-01-16 21:04:02       33 阅读
  3. C++面试之线程池、智能指针、设计模式

    2024-01-16 21:04:02       32 阅读
  4. Redis面试题13

    2024-01-16 21:04:02       26 阅读
  5. 二叉树遍历C++

    2024-01-16 21:04:02       38 阅读
  6. Vue2:利用watch和localStorage存储数据案例

    2024-01-16 21:04:02       36 阅读
  7. JPA查询PostgreSQL行排序问题

    2024-01-16 21:04:02       34 阅读