3 ms·
True, but in my experience the overhead of std::shared_mutex outweighs the benefits. Other approaches include: * breaking up the lock so different threads can
by AndrewStephens 3y ago
True, but in my experience the overhead of std::shared_mutex outweighs the benefits. Other approaches include:
* breaking up the lock so different threads can access different parts of your data structure concurrently.
* double-buffering (also called ping-pong buffers) where you effectively keep two copies of your data structure. The readers can access one without blocking, a single writer can modify the other and then swap.
* just accepting that reads will block each other with a std::mutex and work on minimizing the amount of time spent in the lock. This can actually work out quicker depending on your access patterns.
As always, careful profiling with real data is required to figure out what is better.
- secondcoming 3y agoThe problem with double-buffering is that you still need to know when all the readers are no longer using one of the copies. T1: writer populates copy1 T2: readers access copy1 T3: writer populates copy2, and swaps T4: writer populates copy1, and swaps At T4 a reader from T2 could still be accessing the old data structure. Unless I'm overthinking it.
- AndrewStephens 3y agoNo, you are right. One solution is that the readers access the buffer through a shared_ptr and can hold onto the old version for as long as they need it while the writer makes changes and creates a wholly new data structure. It is also possible for the writer to block new readers while doing the swap. Tradeoffs everywhere, depending on if you need readers to see changes that occurred after they started accessing the data.
- to11mtm 3y agoNope, Ironically ran into this category of issue today with some buffer-reuse in a multi-threaded system.