![github-actions[bot]](/assets/img/avatar_default.png)
* Create rule S7450 * Update metadata.json * Update rule.adoc * Update rule.adoc * Update metadata.json --------- Co-authored-by: sallaigy <sallaigy@users.noreply.github.com> Co-authored-by: Gyula Sallai <gyula.sallai@sonarsource.com>
33 lines
1.1 KiB
Plaintext
33 lines
1.1 KiB
Plaintext
|
|
== Why is this an issue?
|
|
Immediately dropping a synchronization lock (e.g., `mutex`, `rwlock`) after acquiring it using `let _ = sync_lock` is often unintentional and can lead to subtle bugs. By extending the lock lifetime to the end of the scope using a named variable, the code becomes safer and intentions are clearer. If immediate drop is intended, using `std::mem::drop` conveys the intention more clearly and reduces error-prone behavior.
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
[source,rust,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
let _ = Mutex::new(1).lock(); // Noncompliant: Immediately drops the lock.
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,rust,diff-id=1,diff-type=compliant]
|
|
----
|
|
// Extend lock lifetime to end of scope
|
|
let _lock = Mutex::new(1).lock(); // Compliant: Lock remains till scope ends.
|
|
----
|
|
|
|
You can also explicitly drop the lock to convey intention:
|
|
|
|
[source,rust,diff-id=1,diff-type=compliant]
|
|
----
|
|
std::mem::drop(Mutex::new(1).lock()); // Compliant: Clearly drops the lock.
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#let_underscore_lock
|