Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map write/read from multiple threads

Tags:

c++

c++11

I want to be able to read and write in a std::map from multiple threads. Is there a way to do that without mutex (maybe with std::atomic)?

If not, what's the simplest way to do that in C++11?

like image 466
MartinMoizard Avatar asked Apr 27 '15 09:04

MartinMoizard


2 Answers

If the values are std::atomic<>, you can modify and read them from arbitrary threads, but you'll need to have saved their addresses somehow - pointers, references or iterators - and you'll need to know no other thread will call erase on them....

Still, even atomic values won't make it safe to modify the container (e.g. inserting or erasing elements), while other threads are also doing modifications or lookups or iteration. Even the "const" functions - like size(), empty(), begin(), end(), count(), and iterator movement - are unsafe, because the mutating operations may be in the middle of rewiring the inter-node links or updating the same data.

For anything more than the above, you will need a mutex.


For a concrete example, say you've inserted a node with std::string key "client_counter" - you could start a thread that gets an iterator to that element and does atomic updates to the counter, while other threads can find the element and read from it but must not erase it. You could still have other nodes inserted in the map, with other updaters and readers, without any extra synchronisation with the client_counter-updating thread.

like image 156
Tony Delroy Avatar answered Nov 16 '22 22:11

Tony Delroy


If you don't want to use mutex then you need to wait for concurrent containers (C++17?). If you want to use std::atomic operations inside std::map then you probably want to make or found on the Internet fully implementation of concurrent atomic std::map.

If you want to use std::map of std::atomic then you probably need to know that this will protect only elements inside std::map, but not std::map in self.

like image 24
senfen Avatar answered Nov 16 '22 23:11

senfen