user1002288
user1002288

Reputation: 5040

how to define a vector<boost::mutex> in C++ ?

I want to define a vector with boost::mutex like :

  boost::mutex myMutex ;
  std::vector< boost::mutex > mutexVec; 
  mutexVec.push_back(myMutex); 

But, I got error on Linux:

/boost_1_45_0v/include/boost/thread/pthread/mutex.hpp:33: error: âboost::mutex::mutex(const boost::mutex&)â is private /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h:104: error: within this context

I cannot find a solution by searching online.

thanks

Upvotes: 5

Views: 4400

Answers (3)

Ferruccio
Ferruccio

Reputation: 100718

You could use a boost pointer container:

#include <boost/thread.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

boost::ptr_vector<boost::mutex> pv;
pv.push_back(new boost::mutex);

A ptr_vector takes ownership of its pointers so that they are deleted when appropriate without any of the overhead a smart pointer might introduce.

Upvotes: 9

Billy ONeal
Billy ONeal

Reputation: 106609

boost::mutex cannot be stored in a vector because it is not copy constructable. As mentioned in PeterT's answer, it is possible to store pointers to the mutex inside the vector instead, you really should probably reconsider a design which relies on such things. Keep in mind vector itself does not have any threading requirements, and trying to do anything modifying the vector will not be a thread safe operation.

Upvotes: 2

PeterT
PeterT

Reputation: 8284

The copy constructor is private. You aren't supposed to copy a mutex.

Instead use:

boost::mutex *myMutex = new boost::mutex();
std::vector< boost::mutex *> mutexVec; 
mutexVec.push_back(myMutex);

and if you don't want to manage the memory yourself use a boost::shared_ptr<boost::mutex> instead of boost::mutex*

Upvotes: 5

Related Questions