[英]C++ Thread-Safe Map
有誰知道我在哪里可以找到包裝std::map
並使其成為線程安全的隱含內容? 當我說線程安全時,我的意思是說它僅提供對映射的串行訪問,一次僅提供一個線程。 最佳情況下,此映射應僅使用標准庫和/或boost結構。
不符合您指定的條件,但是您可以看一下TBB容器。 有所謂的concurrent_hash_map
,它允許多個線程訪問同時在地圖數據。 有一些細節,但是所有內容都有很好的記錄,可以使您對“並發容器”有所了解。 根據您的需求,這可能是完全不合適的...
收集類提供線程安全性通常不是一個好主意,因為它們不知道如何使用它們。 通過在使用集合的更高級別構造中實現自己的鎖定機制,可以為您提供更好的服務。
在您的約束下,boost shared_mutex將提供最佳的多重讀取器/單個寫入器方法來包裝標准地圖。 我不知道將這兩種方法結合使用的任何“預構建”實現,因為任務通常很簡單。
您可能會看到線程安全模板庫
這取決於應用程序要實現。 “線程安全”映射將使各個調用成為線程安全的映射,但是許多操作需要在調用之間變為線程安全。 使用該映射的應用程序應將一個互斥鎖與該映射相關聯,並使用該互斥鎖來協調對其的訪問。
嘗試制作線程安全的容器在Java中是一個錯誤,而在C ++中則是一個錯誤。
試試這個圖書館
http://www.codeproject.com/KB/threads/lwsync.aspx
它是基於現代c ++策略的方法實現的。
這是從鏈接中截取的一些內容,以“矢量”情況說明
typedef lwsync::critical_resource<std::vector<int> > sync_vector_t;
sync_vector_t vec;
// some thread:
{
// Critical resource can be naturally used with STL containers.
sync_vector_t::const_accessor vec_access = vec.const_access();
for(std::vector<int>::const_iterator where = vec_access->begin();
where != vec_access->end();
++where;
)
std::cout << *where << std::endl;
}
sync_vector_t::accessor some_vector_action()
{
sync_vector_t::accessor vec_access = vec.access();
vec_access->push_back(10);
return vec_access;
// Access is escalated from within a some_vector_action() scope
// So that one can make some other action with vector before it becomes
// unlocked.
}
{
sync_vector_t::accessor vec_access = some_vector_action();
vec_access->push_back(20);
// Elements 10 and 20 will be placed in vector sequentially.
// Any other action with vector cannot be processed between those two
// push_back's.
}
我想出了這一點(我敢肯定,可以接受兩個以上的論點進行改進):
template<class T1, class T2>
class combine : public T1, public T2
{
public:
/// We always need a virtual destructor.
virtual ~combine() { }
};
這使您可以執行以下操作:
// Combine an std::mutex and std::map<std::string, std::string> into
// a single instance.
combine<std::mutex, std::map<std::string, std::string>> lockableMap;
// Lock the map within scope to modify the map in a thread-safe way.
{
// Lock the map.
std::lock_guard<std::mutex> locked(lockableMap);
// Modify the map.
lockableMap["Person 1"] = "Jack";
lockableMap["Person 2"] = "Jill";
}
如果您想使用std :: recursive_mutex和std :: set,那也可以。
這里有一個命題(對我來說,是無恥的插件),它包裝對象(包括STL
容器)以進行有效的(零成本)線程安全訪問:
https://github.com/isocpp/CppCoreGuidelines/issues/924
基本思想很簡單。 只有少數包裝器類用於強制執行讀/寫鎖定,同時提供包裝對象的const(只讀)或非const(讀寫)視圖。
這樣做的想法是使編譯時無法正確訪問線程之間共享的資源。
實現代碼可以在這里找到:
https://github.com/galik/GSL/blob/lockable-objects/include/gsl/gsl_lockable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.