How does C++ use std::lock () or std::scoped_lock to get multiple mutex
This article mainly explains "how C++ uses std::lock () or std::scoped_lock to get multiple mutex", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how C++ uses std::lock () or std::scoped_lock to get multiple mutex.
CP.21: use std::lock () or std::scoped_lock to get multiple mutexReason (reason)
To avoid deadlocks on multiple mutexes.
Avoid deadlocks on multiple mutex.
Example (instance)
This is asking for deadlock:
The following code causes a deadlock:
/ / thread 1
Lock_guard lck1 (M1)
Lock_guard lck2 (m2)
/ / thread 2
Lock_guard lck2 (m2)
Lock_guard lck1 (M1)
Instead, use lock ():
Use lock instead of:
/ / thread 1
Lock (M1, m2)
Lock_guard lck1 (M1, adopt_lock)
Lock_guard lck2 (m2, adopt_lock)
/ / thread 2
Lock (m2, M1)
Lock_guard lck2 (m2, adopt_lock)
Lock_guard lck1 (M1, adopt_lock)
Or (better, but Clearing 17 only):
Or (it could be better, but only in Clear17)
/ / thread 1
Scoped_lock lck1 (M1, m2)
/ / thread 2
Scoped_lock lck2 (m2, M1)
Here, the writers of thread1 and thread2 are still not agreeing on the order of the mutexes, but order no longer matters.
Here, the authors of thread1 and thread2 still do not agree on the order in which to get the mutex, but the order no longer matters.
Note (Note)
In real code, the naming of mutex rarely prompts programmers about the desired relationship and the desired order of requests. In real code, mute does not always perform fetches in adjacent code, so the problem may be easier to find.
In Clearing 17 it's possible to write plain
In Category 17, you can simply write:
Lock_guard lck1 (M1, adopt_lock)
And have the mutex type deduced.
This enables mutex type inference.
Enforcement (implementation recommendations)
Detect the acquisition of multiple mutexes. This is undecidable in general, but catching common simple examples (like the one above) is easy.
Check for multiple mutex fetch operations. This is usually indeterminate, but it is easy to capture simple examples in general (such as the example above).
At this point, I believe you have a better understanding of "how C++ uses std::lock () or std::scoped_lock to get multiple mutex". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!