为什么 c++11 std::lock 和 std::scoped_lock 至少需要 2 个参数?

Why c++11 std::lock and std::scoped_lock need at least 2 parameters?

刚刚发现这2个utils至少需要2个参数,例如2 个互斥锁。

需要这样(来自cppreference.com):

void assign_lunch_partner(Employee &e1, Employee &e2)
{
    static std::mutex io_mutex;
    {
        std::lock_guard<std::mutex> lk(io_mutex);
        std::cout << e1.id << " and " << e2.id << " are waiting for locks" << std::endl;
    }

    {
        std::scoped_lock lock(e1.m, e2.m);
    }
}

要求至少 2 个参数有意义吗?设计的考虑是什么,希望了解更多详情。

非常感谢。

不需要两个,它可以锁定一个或多个

cppreference page 你的例子中(强调我的):

The class scoped_lock is a mutex wrapper that provides a convenient RAII-style mechanism for owning one or more mutexes for the duration of a scoped block.

std::scoped_lock 是获取多个互斥量的便捷实用程序 - 它将在后台使用 死锁避免机制 。在 C++11 和 C++14 中我们只有 std::lock(),但它不是 RAII 机制(它不会自动解锁互斥量)。

您也可以将 std::scoped_lock 与单个互斥锁一起使用,然后它就等同于 std::lock_guard