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