I'm trying to lock multiple mutexes without a deadlock while also making sure no threads block forever. From what I understand, std::scoped_lock()
calls std::lock()
to acquire its locks--which is blocking. I'm worried about the poor, unlucky thread that never catches a break and always fails to acquire all of the locks when multiple locks are needed amidst a lot of concurrent access.
I get that critical sections should be as small and fast as possible; one needs to get in and out as quickly as possible to avoid long blocking times. But surely even locking well-written code and critical sections can stress the mutex resources given enough concurrent requests.
I looked at using std::timed_mutex
with std::scoped_lock()
, but std::timed_mutex::lock()
blocks and doesn't make use of the mutex's timed capability (would require std::timed_mutex::try_lock_for()
or std::timed_mutex::try_lock_until()
, which as far as I know isn't used by std::scoped_lock()
).
So is there a way to lock multiple mutexes and guarantee that no thread will block forever while waiting to lock the mutexes (even if that means it doesn't acquire any locks)? Is there a non-blocking version of std::scoped_lock()
? Can you break a blocked std::scoped_lock()
call? Should I expect the scenario of a thread blocking forever to be so rare that it's an acceptable risk? Am I thinking too hard?