1

In my application, multiple threads need to access to a map object for inserting new items or reading the existing items. (There is no 'erase' operation).

The threads uses this code for accessing map elements:

struct PayLoad& ref = myMap[index];

I just want to know do I still need to wrap this block of this code inside of mutex ? Or is it safe to not using mutex for this purpose ?

Thanks.

atari83
  • 489
  • 1
  • 5
  • 15
  • 3
    No, it is not thread safe to add items to a map from multiple threads. So yes, you need to use a mutex or some other form of synchronization – UnholySheep Sep 03 '22 at 19:10

1 Answers1

2

Since there is at least one write operation, i.e. an insert, then you need to have thread synchronization when accessing the map. Otherwise you have a race condition.

Also, returning a reference to the value in a map is not thread-safe:

struct PayLoad& ref = myMap[index];

since multiple threads could access the value, and at least one of them could involve a write. That would also lead to a race condition. It is better to return the value by value like this:

Payload GetPayload(int index)
{
    std::lock_guard<std::mutex> lock(mutex);
    return myMap[index];
}

where mutex is an accessible std::mutex object.

Your insert/write operation also needs to lock the same mutex:

void SetPayload(int index, Payload payload)
{
    std::lock_guard<std::mutex> lock(mutex);
    myMap[index] = std::move(payload);
}
jignatius
  • 6,304
  • 2
  • 15
  • 30