栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++11 future 与 thread

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++11 future 与 thread

#pragma once

#include 
#include 
#include 
#include 
#include 

using std::cout;
using std::endl;

class Test_threadLocal
{
    typedef Test_threadLocal self_type;

    class ThreadLocalData
    {
    public:
        ThreadLocalData()
        {
            cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << endl;
        }

        ~ThreadLocalData()
        {
            cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << endl;
        }
    };

private:
    bool entry()
    {
         thread_local ThreadLocalData data;
         return true;
    }

    void runWithThread()
    {     
        cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " begin ******************************" << endl;
        std::vector> threadGroup;
        const int threadCount = 5;
        for (int i = 0; i < threadCount; ++i)
        {
            std::shared_ptr t(new std::thread(&self_type::entry,this));
            threadGroup.push_back(t);
        }

        for (int i = 0; i < threadCount; ++i)
        {
            threadGroup[i]->join();
        }

        cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " end ******************************" << endl;
        int a = 5;
        ++a;
    }

    void runWithFuture()
    {
        cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " begin ******************************" << endl;
        std::vector< std::future > futureList;
        const int threadCount = 5;
        for (int i = 0; i < threadCount; ++i)
        {
            futureList.push_back(std::async(std::launch::async, &self_type::entry, this));
        }

        bool bSuccess = true;
        for (auto& f : futureList)
        {
            bool rtn = f.get();
            cout << "rtn:" << rtn << endl;
        }

        cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " end ******************************" << endl;
        int a = 5;
        ++a;
    }

public:
    static void test()
    {
        self_type obj;
        obj.runWithThread();
        obj.runWithFuture();
    }
};

发现: runWithThread执行完毕后,正常调用 ThreadLocalData 析构函数

            runWithFuture执行完毕后,并未调用 ThreadLocalData 析构函数 (这是个问题)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/655397.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号