std::lock_guard or std::scoped_lock?

前端 未结 4 794
说谎
说谎 2020-11-27 10:35

C++17 introduced a new lock class called std::scoped_lock.

Judging from the documentation it looks similar to the already existing std::lock_guard clas

4条回答
  •  执念已碎
    2020-11-27 11:01

    Here is a sample and quote from C++ Concurrency in Action:

    friend void swap(X& lhs, X& rhs)
    {
        if (&lhs == & rhs)
            return;
        std::lock(lhs.m, rhs.m);
        std::lock_guard lock_a(lhs.m, std::adopt_lock);
        std::lock_guard lock_b(rhs.m, std::adopt_lock);
        swap(lhs.some_detail, rhs.some_detail);
    }
    

    vs.

    friend void swap(X& lhs, X& rhs)
    {
        if (&lhs == &rhs)
            return;
        std::scoped_lock guard(lhs.m, rhs.m);
        swap(lhs.some_detail, rhs.some_detail);
    }
    

    The existence of std::scoped_lock means that most of the cases where you would have used std::lock prior to c++17 can now be written using std::scoped_lock, with less potential for mistakes, which can only be a good thing!

提交回复
热议问题