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?
Asked
Active
Viewed 232 times
0
-
Are all threads of same priority? – Erik Alapää Jan 31 '18 at 12:11
-
See also https://stackoverflow.com/questions/12685112/pthreads-thread-starvation-caused-by-quick-re-locking – Erik Alapää Jan 31 '18 at 12:17
1 Answers
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 c++17 or std::shared_timed_mutex
in c++14 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