Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add boost threads to a vector

Tags:

c++

boost

I have something like this that is incorect:

vector<boost::thread> vec;
for(int agent = 1; agent <= numAgents; ++agent)
{
    boost::thread agentThread(sellTickets, agent, numTickets/numAgents);
    vec.push_back(agentThread);
}

Maybe i should add pointers to boost::thread in the vector, but then I don't know how to add dynamic allocated threads, how should I do to make this work ?

Thank you.

like image 966
Adrian Avatar asked Mar 24 '11 08:03

Adrian


People also ask

What is boost thread C++?

Thread enables the use of multiple threads of execution with shared data in portable C++ code. The Boost. Thread library was originally written and designed by William E.

Is Vector thread safe in C++?

const and Thread Safety The C++11 standard does not expect to be able to safely call non const functions simultaneously. Therefore all classes available from the standard, e.g. std::vector<>, can safely be accessed from multiple threads in the same manner.

Does boost use Pthread?

Boost. Sync supports building against one of the following underlying APIs: pthreads or Windows API. On most platforms pthreads are the only option. On Windows, Windows API is used by default, but pthreads can be enabled.


1 Answers

  • You must have a compiler with move-semantics supported in order to make your code work,
  • or use vector<shared_ptr<boost::thread>> with code like:

    vec.push_back(make_shared<boost::thread>(sellTickets, agent, numTickets/numAgents));
    
  • or use boost::thread_group.

like image 180
Yakov Galka Avatar answered Sep 27 '22 20:09

Yakov Galka