Issue 209112
Summary [clang-tidy] `modernize-use-scoped-lock` suggests `scoped_locks`, but only warns about multiple `lock_guards`
Labels clang-tidy
Assignees
Reporter dey4ss
    With `modernize-use-scoped-lock`, clang-tidy suggests to use `scoped_lock`s instead of, e.g., `lock_guard`s, because `scoped_lock`s can lock multiple mutexes with a deadlock-avoidance algorithm.

The rule warns about two things:
1. Two `lock_guards` in a the same scope that can cause a deadlock.
2. _Any_ use of `lock_guard`. This behavior can be turned off with setting `WarnOnSingleLocks` to false.

With the default configuration, clang-tidy guides users to write problematic code that it cannot detect anymore: all `lock_guard`s will be replaced by `scoped_lock`. If a new `scoped_lock` is added in the scope, there is no warning.

The issue that motivated the rule (#107839) already suggested to add a check for multiple `scoped_locks`, but it seems this suggestion was not picked up.

Example:
```c++
#include <mutex>

void one_lock_guard() {
  auto mutex = std::mutex{};

  // One `lock_guard`. clang-tidy suggests to use `scoped_lock`.
  const auto lock = std::lock_guard{mutex};
}

void one_scoped_lock() {
  auto mutex1 = std::mutex{};
  auto mutex2 = std::mutex{};

  // `scoped_lock` with deadlock avoidance, correct.
 const auto lock = std::scoped_lock{mutex1, mutex2};
}

void two_lock_guards() {
  auto mutex1 = std::mutex{};
  auto mutex2 = std::mutex{};

  // Two `lock_guards`, deadlock-prone. clang-tidy complains.
  const auto lock1 = std::lock_guard{mutex1};
  const auto lock2 = std::lock_guard{mutex2};
}

void two_scoped_locks() {
  auto mutex1 = std::mutex{};
  auto mutex2 = std::mutex{};

  // Two `lock_guards`, deadlock-prone. clang-tidy does not complain.
  const auto lock1 = std::scoped_lock{mutex1};
  const auto lock2 = std::scoped_lock{mutex2};
}
```

Godbolt link: [https://godbolt.org/z/f9zfaaEoY](https://godbolt.org/z/f9zfaaEoY)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to