0

The following situation occured in some code I found. A lot (about 10) of threads use one mutex to write or read from a map. The mutex locking is done with a lock_guard. My question is about the situation where the thread number increased and 10 threads are waiting at the same time for the mutex. I know that there is no guarantee on the order. Are there any side effects on this situation? Is there at least a guarantee that every thread is able to lock the mutex or may there be threads that never get a chance to access the data structure because others are faster?

Gustavo
  • 919
  • 11
  • 34

1 Answers1

1

What you seem to be asking about is starvation -- can a thread never get access to the mutex if it is always in contention.

std::mutex is not "fair". More than that, it is not starvation-safe. There are no forward progress guarantees for individual threads in that situation.

You can create a more complex data structures that guarantee fairness or even forward progress, but they have more overhead.

You might want to consider using a std::shared_mutex in or std::shared_timed_mutex in to reduce contention, as that would permit multiple readers to clear out of the way faster.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • I think I mean starvation. At the moment, there is no C++17 support for me. A simple solution for now could be using a condition variable to tell other threads that the resource is free. – Gustavo Feb 01 '18 at 11:12