46 lines
1.2 KiB
Plaintext
46 lines
1.2 KiB
Plaintext
``++std::scoped_lock++`` basically provides the same feature as ``++std::lock_guard++``, but is more generic: It can lock several mutexes at the same time, with a deadlock prevention mechanism (see S5524). The equivalent code to perform simultaneous locking with ``++std::lock_guard++`` is significantly more complex. Therefore, it is simpler to use ``++std::scoped_lock++`` all the time, even when locking only one mutex (there will be no performance impact).
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,cpp]
|
|
----
|
|
void f1(std::mutex &m1) {
|
|
std::lock_guard lock{m1}; // Noncompliant
|
|
// Do some work
|
|
}
|
|
|
|
void f2(std::mutex &m1, std::mutex &m2)
|
|
std::lock(m1, m2);
|
|
std::lock_guard<std::mutex> lock1{m1, std::adopt_lock}; // Noncompliant
|
|
std::lock_guard<std::mutex> lock2{m2, std::adopt_lock}; // Noncompliant
|
|
// Do some work
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,cpp]
|
|
----
|
|
void f1(std::mutex &m1) {
|
|
std::scoped_lock lock{m1}; // Compliant
|
|
// Do some work
|
|
}
|
|
|
|
void f2(std::mutex &m1, std::mutex &m2)
|
|
std::scoped_lock lock{m1, m2}; // Compliant, and more simple
|
|
// Do some work
|
|
}
|
|
----
|
|
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|