Thread Safety in C ++

I have a question regarding thread safety, as shown below (I have only two streams in which one of the streams is read only from the card, the other streams will write and read as shown):

//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 

What is the correct way to block unordered_map? Also, should I use a single lock or multiple locks?

Thanks.

+4
source share
3 answers

If your card is the only shared resource, one mutex is enough.

You need to commit a record in the first thread and block reading in the second. If you lock the card only when writing to it, the second thread can read it , and that you write in it.

In the last example, concerning pointers, you do not need a lock, since you are not dealing with data stored on a map. Edit: It really depends on what you do with pointers and in which thread you do it.

You should read this wonderful article: http://herbsutter.com/2010/09/24/effective-concurrency-know-when-to-use-an-active-object-instead-of-a-mutex/

+2
source

You need to block both reading and writing. If you do not block reading, then reading may occur and you can access the card in an inconsistent state.

What would be better in your situation is a read-write lock. This lock allows multiple readers to be read at the same time, but only one writer at a time, and there are no readers when the writer writes, and vice versa.

+1
source

A couple of things:

  • You should consider smart pointers to save on your map.
  • What you do is potentially dangerous (i.e. you cannot change the main map), but you change what was stored there, and if you do it outside of the lock, the end result could be anything - let's say thread one also reads the same pointer and starts iterating while thread two writes an instance of class A - what happens next?

I would have a lock around the main card, and then another lock for each payload card. Any operations on any card must require a lock at the correct level. I would also be careful not to return iterators outside the class that controls locking, so basically you should implement all the methods you need in the class.

0
source

All Articles