c++ - C++中的线程安全

标签 c++

我有如下关于线程安全的问题(我只有两个线程,其中一个线程只从映射中读取,其他线程将写入和读取,如图所示):

//Thread 2: the reading and writing thread
unordered_map<int, unordered_map<classA*>*>testMap;

//need lock because writing to the map?
testMap[1] = new unordered_map<int, classA*>;

//do not need lock because only reading and the other thread is only reading?
unordered_map<classA*>* ptr = testMap[1];

//need lock because writing?
(*ptr)[1] = new classA;

//do not need lock because only reading and the other thread is only reading?
classA* ptr2 = (*ptr)[1];

//din't modify the map, but modify the data pointed by the pointer stored by the map, do I need lock?
ptr2->field1 = 5;
ptr2->field2 = 6;

//end of reading and writing thread

锁定到 unordered_map 的正确方法是什么?另外,我应该使用单锁还是多锁?

谢谢。

最佳答案

如果您的 map 是唯一的共享资源,则单个互斥量就足够了。

需要在第一个线程中锁定写入,在第二个线程中锁定读取。如果您仅在 map 上书写时才锁定 map ,则第二个线程可以在您正在其中书写时读取它。

在上一个关于指针的示例中不需要锁,因为您不处理映射中存储的任何数据。 编辑:事实上,这取决于您使用指针做什么以及您在哪个线程中执行此操作。

您应该阅读这篇很棒的文章:http://herbsutter.com/2010/09/24/effective-concurrency-know-when-to-use-an-active-object-instead-of-a-mutex/

关于c++ - C++中的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4364663/

相关文章:

c++ - 在 Windows 上获取 boost::filesystem::path 作为 UTF-8 编码的 std::string

c++ - 对于类型 Class::Type,我可以从 const Class 派生 const Class::Type 吗?

c++ - CMake:提取 tar 会出现错误,但没有消息

c++ - 使用没有模板的模板化类

c++ - 在 C++ 应用程序中链接到错误的库版本

c++ - 无法包含 DirectShow 示例并对其进行编译 (PushSourceDesktop)

c++ - 主类中有多个派生类的重新定义错误

c++ - ROS_INFO_STREAM 不打印

c++ - for循环中有多个输入

c++ - 二进制搜索树读取字符串? C++