【问题标题】:How can man put a thread(in boost) which is created with packaged_task, into a shared_ptr vector人如何将使用 packaged_task 创建的线程(在 boost 中)放入 shared_ptr 向量中
【发布时间】:2015-06-23 11:17:58
【问题描述】:

这是来自 boost 库的示例。

int calculate_the_answer_to_life_the_universe_and_everything()
    {
      return 42;
    }

boost::packaged_task<int> pt(calculate_the_answer_to_life_the_universe_and_everything);
boost:: future<int> fi=pt.get_future();

而不是boost::thread task(boost::move(pt)); 在线程上启动任务,
现在我想将线程放入 shared_ptr 向量并在线程上启动一个任务。

首先我创建一个向量。

std::vector<std::shared_ptr<boost::thread>> vecThreads;

这是将线程放入向量的正确方法吗?

vecThreads.push_back(std::make_shared<boost::thread>(boost::packaged_task<int> &pt));

感谢大家的关注!

【问题讨论】:

    标签: multithreading boost vector shared-ptr make-shared


    【解决方案1】:

    打包任务就是这样。他们没有“有”线程。 他们只是在一个线程上运行。任何线程。

    实际上,为每个任务启动一个线程是一种反模式。但是,当然,你可以。我建议使用

    boost::thead_group tg;
    tg.create_thread(std::move(pt));
    

    所以你可以依赖

    tg.join_all();
    

    等待所有待处理的线程完成。

    更新

    使用共享指针,这里有一个例子:

    Live On Coliru

    #include <boost/thread.hpp>
    #include <boost/make_shared.hpp>
    #include <boost/bind.hpp>
    
    using namespace boost;
    
    int ltuae(int factor) {
        this_thread::sleep_for(chrono::milliseconds(rand()%1000));
        return factor*42;
    }
    
    int main() {
        std::vector<unique_future<int> > futures;
        std::vector<shared_ptr<thread> > threads;
        for (int i=0; i<10; ++i)
        {
            packaged_task<int> pt(bind(ltuae, i));
            futures.emplace_back(pt.get_future());
            threads.emplace_back(make_shared<thread>(std::move(pt)));
        }
    
        for (auto& f : futures)
            std::cout << "Return: " << f.get() << "\n";
    
        for (auto& t: threads)
            if (t->joinable())
                t->join();
    }
    

    【讨论】:

    • 出于某种原因,我必须使用 shared_ptr 向量来存储一些线程。你有什么秘诀吗?谢谢
    • @rayallen 添加了一个简单的示例live on Coliru
    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2016-04-18
    相关资源
    最近更新 更多