zoukankan      html  css  js  c++  java
  • C++ std::thread的基础使用和管理

    1. 基本的介绍和使用

    参考菜鸟教程的相关介绍,涉及各种构造函数和其他成员函数的使用。

    https://www.runoob.com/w3cnote/cpp-std-thread.html

    下面这篇文章也有比较丰富的使用例子:

    https://blog.csdn.net/ouyangfushu/article/details/80199140

    下面这篇阐述了创建线程的三种方式(1)函数(2)类对象(3)Lambda表达式

    https://blog.csdn.net/fly_wt/article/details/88986993

    2. 用shared_ptr进行多个线程的管理

    主要面临的问题是这样的:

    (1)在一个程序之中,主线程会创建多个线程执行不同的任务,主线程不需要被阻塞;

    (2)主线程最后会执行一系列清理任务,这些清理任务执行之前需要等待所有的子线程执行完毕。

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <vector>
    #include <thread>
    #include "windows.h"
    using namespace std;
    
    class ThreadTest
    {
    public:
    	void normalthread()
    	{
    		cout<<"Normal thread" << to_string(count++) << endl;
    	}
    
    	void endthread()
    	{
    		for (auto iter = m_threadlist.begin(); iter != m_threadlist.end();iter++)
    		{
    			(*iter)->join();
    		}
    		cout << "End Thread" << endl;
    	}
    
    	void run()
    	{
    		for (int i = 0; i < 10; i++)
    		{
    			Sleep(10);
    			m_threadlist.push_back(make_shared<thread>(&ThreadTest::normalthread,this));
    		}
    
    		m_endThread = make_shared<thread>(&ThreadTest::endthread, this);
    		m_endThread->join();
    	}
    
    private:
    	uint32_t count;
    	vector<shared_ptr<thread>> m_threadlist;
    	shared_ptr<thread> m_endThread;
    };
    

      程序当中需要注意的点有以下几个:

    (1)thread的管理使用一个vector<shared_ptr<thread>>而不是thread本身的vector,避免thread本身的拷贝构造;

    (2)再向thread的vector插入元素的时候,make_shared<thread>的参数需要传递函数指针和类的this指针。

      相关讨论:https://segmentfault.com/q/1010000015755911?utm_source=tag-newest

  • 相关阅读:
    final finally finalize区别
    final 有什么用
    Java基础(一) 八大基本数据类型
    22
    21
    20
    18
    17
    16
    15
  • 原文地址:https://www.cnblogs.com/stonemjl/p/12530864.html
Copyright © 2011-2022 走看看