17

有谁知道我在哪里可以找到包装 astd::map并使其线程安全的暗示?当我说线程安全时,我的意思是它只提供对映射的串行访问,一次一个线程。理想情况下,此地图应仅使用标准库和/或增强结构。

4

8 回答 8

13

不符合您指定的标准,但您可以查看TBB容器。有所谓concurrent_hash_map的允许多个线程同时访问映射中的数据。有一些细节,但所有内容都有很好的文档记录,可以让您了解“并发容器”。根据您的需要,这可能是完全不合适的......

于 2009-05-04T15:28:24.397 回答
3

boost shared_mutex 将提供最佳的多读取器/单写入器方法来包装标准映射给定您的约束。我不知道任何与这两者结合的“预建”实现,因为任务通常是微不足道的。

于 2009-05-04T15:15:22.477 回答
2

集合类提供线程安全通常不是一个好主意,因为它们不知道它们是如何被使用的。通过在使用集合的更高级别的构造中实现自己的锁定机制,您将获得更好的服务。

于 2009-05-04T15:18:00.350 回答
1

试试这个库

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.
}
于 2009-05-04T15:20:30.343 回答
1

您可能会查看线程安全模板库

于 2010-09-10T18:53:34.597 回答
1

我想出了这个(我确信可以改进它以采用两个以上的参数):

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,那也可以。

于 2018-01-26T20:06:29.143 回答
0

这里有一个命题(由我 - 无耻插件)包装对象(包括STL容器)以实现高效(零成本)线程安全访问:

https://github.com/isocpp/CppCoreGuidelines/issues/924

基本思想非常简单。只有几个包装类用于强制读/写锁定,同时呈现包装对象的 const(用于只读)或非 const(用于读写)视图。

这个想法是使编译时不可能不正确地访问线程之间共享的资源。

实现代码可以在这里找到:

https://github.com/galik/GSL/blob/lockable-objects/include/gsl/gsl_lockable

于 2018-06-20T14:30:42.067 回答
-1

这取决于应用程序来实现。“线程安全”映射将使对映射的单独调用成为线程安全的,但许多操作需要调用之间实现线程安全。使用映射的应用程序应将互斥锁与映射关联,并使用该互斥锁来协调对其的访问。

尝试制作线程安全的容器在 Java 中是一个错误,在 C++ 中也是一个错误。

于 2009-05-04T15:15:49.200 回答