0

Just found that these 2 utils needs at least 2 parameters, e.g. 2 mutex to lock.

Needs to be like this(from 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);
    }
}

Does it make any sence to require at lease 2 params? What was the design consideration, wish to know more details.

Thanks a lot.

Gaurav Dhiman
  • 1,163
  • 6
  • 8
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

2

It doesn't require two, it can lock one or more.

From the cppreference page you took your example from (emphasis mine):

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 is a convenience utility for acquiring multiple mutexes - it will use deadlock avoiding mechanism under the hood. In C++11 and C++14 we only had std::lock(), but it is not a RAII mechanism (it will not unlock mutexes automatically).

You can also use std::scoped_lock with single mutex, then it becomes equivalent to std::lock_guard

Community
  • 1
  • 1
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52