How can man put a thread(in boost) which is created with packaged_task, into a shared_ptr vector

233 views Asked by At

this is a example from boost library.

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();

instead of boost::thread task(boost::move(pt)); to launch a task on the thread,
now I want to put the thread into shared_ptr vector and launch a task on the thread.

First i creat a vector.

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

And is this the right way to put a thread into vector?

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

thank you all for the attention!

1

There are 1 answers

2
sehe On BEST ANSWER

Packaged tasks are just that. They don't "have" threads. They just run on a thread. Any thread.

In fact, it's an anti-pattern to start a thread for each task. But, of course, you can. I'd suggest using a

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

So you can depend on

tg.join_all();

to await all pending threads completion.

UPDATE

With shared pointers, here's an example:

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();
}