5
votes

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

3
What is mutexVec.push_back(myMutex); expected to do?curiousguy

3 Answers

9
votes

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.

5
votes

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*

2
votes

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.