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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With