Semin Park
Semin Park

Reputation: 782

What counts as "write" to std::map?

I'm working on a multithreaded application that uses a std::map underneath. I am aware that writing to std::map is not thread safe and I need to lock the tree when I'm writing.

However, I couldn't find a definition of "writing". Does it only include operations that insert or remove elements from the tree? Or does modifying an element's value in the tree also count as a write?

Consider std::map<int, MyClass> Test, where MyClass has a member variable int x.

Let's say MyClass& t = Test.at(7);. Is t.x++ then considered a write to the map?

Upvotes: 2

Views: 193

Answers (2)

eerorika
eerorika

Reputation: 238301

What counts as “write” to std::map?

Depends on context.

Or does modifying an element's value in the tree also count as a write?

It counts as a write to that element.

It doesn't count as a modification of the tree structure. As such, it is thread safe to modify one map element and concurrently read other elements or traverse the map - while it is indeed not safe to do so when concurrently inserting or erasing elements without synchronisation.

Whether you need synchronisation to read and modify the same element concurrently depends on whether the element object is thread safe.


Standard doesn't explicitly require or guarantee that std::map is a tree. But it is always implemented using a tree.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

Is t.x++ then considered a write to the map?

Yes. You are updating the value of an item in the map. That is writing to the map.

It's analogous to updating the value of an element in an array.

int array[5] = {};
int& item = array[2];
++item;  // This is writing to the array.

In your case,

MyClass& t = Test.at(7);

returns a reference to an item in the map. If value of t is updated, the map is also updated.


Another clue to get an answer to that question is the return value of a std::map::at() for a const object.

T& at( const Key& key );
const T& at( const Key& key ) const;

As you can see, the library doesn't allow you to modify the returned object of the call to std::map::at() for a const object. I.e. the library deems any modifications to the returned value of the function to be a modification of the std::map object.

Upvotes: 2

Related Questions