Skip to content

[clang-tidy] New check: Prefer std::scoped_lock over std::lock_guard #107839

@SunBlack

Description

@SunBlack

In addition to the Clang-Tidy and compiler warnings, we also use other static analysis tools. One of them points out that with C++17 there is actually no longer any reason to use std::lock_guard, since std::scoped_lock is supposed to be identical in terms of performance, but also uses additional deadlock protection mechanisms if several mutexe are to be locked at the same time. You should therefore always use std::scoped_lock so that it is more uniform in the code, even if you may not have any advantages in a specific case.

Example:

std::lock_guard lock(myMutex);
// a bit code
std::lock_guard lock2(myMutex2);
std::lock_guard lock3(myMutex3);

Automatic fix could lock like this:

std::scoped_lock lock(myMutex);
// a bit code
std::scoped_lock lock2(myMutex2, myMutex3);

Notes:

  • I'm not sure if an auto fix can merge multiple std::scoped_lock in a row, as I don't know if it's okay to automatically use the variable name of the first std::scoped_lock, or if it would be better to make it 2 checks instead: readability-prefer-scoped_lock & bugprone-uncombined-scoped_lock.
  • There is also the std::unique_lock, where you can often use std::scoped_lock instead (if the lock does not have to be moved and does not get any extra parameters). This transition is not so trivial, but would possibly speak in favor of packing the transition and the merging of locks into 2 different checks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions