Search code examples
c++multithreadingmutex

accessing to map in multithreaded environment


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.


Solution

  • 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);
    }