How to use boost :: mutex as a display type in std :: map?

I would like to lock the keys / index on another card as follows:

std::map<int, boost::mutex> pointCloudsMutexes_; pointCloudsMutexes_[index].lock(); 

However, I get the following error:

 /usr/include/c++/4.8/bits/stl_pair.h:113: error: no matching function for call to 'boost::mutex::mutex(const boost::mutex&)' : first(__a), second(__b) { } ^ 

It seems to work with std::vector , but not with std::map . What am I doing wrong?

+5
source share
2 answers

In C ++, before C ++ 11, the displayed type std::map must be both constructive by default and copied constructive when operator[] called. However, boost::mutex explicitly designed so that it is not available for copying, since it is generally unclear what the semantics of copying the mutex should be. Due to the fact that boost::mutex not copied, the insertion of such a value using pointCloudsMutexes_[index] not performed.

The best workaround is to use some general pointer to boost::mutex as the display type, for example:

 #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/thread/mutex.hpp> #include <map> struct MyMutexWrapper { MyMutexWrapper() : ptr(new boost::mutex()) {} void lock() { ptr->lock(); } void unlock() { ptr->unlock(); } boost::shared_ptr<boost::mutex> ptr; }; int main() { int const index = 42; std::map<int, MyMutexWrapper> pm; pm[index].lock(); } 

PS: C ++ 11 removed the requirement for the display type to be available for copy.

+4
source

The map requires a copy constructor, but unfortunately boost::mutex does not have an open copy constructor. Mutex is announced below:

 class mutex { private: pthread_mutex_t m; public: BOOST_THREAD_NO_COPYABLE(mutex) 

I don’t think the vector works either, it should have the same problem. Can you push_back a boost::mutex to a vector?

+1
source

Source: https://habr.com/ru/post/1246601/


All Articles