2016-04-07 59 views
5

我想鎖定按鍵/指數在另一張圖是這樣的:如何使用boost :: mutex作爲std :: map中的映射類型?

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

不過,我收到以下錯誤:

/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) { } 
          ^

這似乎與std::vector工作,但不std::map。我究竟做錯了什麼?

+2

有人想知道什麼要求導致了設計決定,即互斥鎖地圖是一種有效的解決方案。有可能有一個更加優雅的方式來實現你想要的。 –

+0

併發散列映射 – Raaj

+0

本設計不會是並行散列映射。這將是一個非併發的互斥鎖地圖。你需要包裹整個地圖,並用一個互斥鎖保護它。 –

回答

4

在C++之前C++ 11,std::map的映射類型必須是默認constructible和拷貝構造,主叫operator[]時。然而,boost::mutex被明確設計爲不可複製構造,因爲通常不清楚複製互斥體的語義應該是什麼。由於boost::mutex不可複製,因此使用pointCloudsMutexes_[index]插入此值無法編譯。

最好的解決方法是使用一些共享指針boost::mutex作爲映射類型,e.g:

#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除去要求爲映射的類型要被複制構造的。

+0

你說''「C++ 11刪除了對映射類型的要求是可複製的」',所以作者的代碼應該在C++ 11下編譯? –

+0

@AlexeyAndronov是的。剛剛嘗試過這個問題的代碼示例,並且在索引爲int時編譯。 – jotik

+0

它不會在我的MSVS2015 update2上用'std :: map'和'std :: mutex'通過X_x –

1

映射需要一個拷貝構造函數,但不幸的是boost::mutex沒有公共拷貝構造函數。互斥體聲明如下:

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

我不認爲矢量也可以,它應該有同樣的問題。你可以push_backboost::mutex成矢量嗎?

+0

互斥互斥不可複製並不「不幸」 - 這非常幸運。它表示不得移動的底層數據結構。 –

+0

@Richard我同意:) –

相關問題