gpt4 book ai didi

c++ - 如何理解scoped_lock的析构函数?cppreference是不是出错了?

转载 作者:行者123 更新时间:2023-12-04 12:21:34 24 4
gpt4 key购买 nike

 ~scoped_lock()
{ std::apply([](auto&... __m) { (__m.unlock(), ...); }, _M_devices); }
如何理解 [](auto&... __m) { (__m.unlock(), ...); ?我不明白 ...在 lambda 中,我不知道这是如何以相反的顺序实现释放互斥锁的。
正如@HolyBlackCat 所说, (__m.unlock(), ...)意味着 (__m1.unlock(),(__m2.unlock(), (__m3.unlock(), (...)))) ,但不实现逆序解锁。
在 cppreference.com 中:

When control leaves the scope in which the scoped_lock object was created, the scoped_lock is destructed and the mutexes are released, in reverse order.


我做了一个实验来确认这一点,如下所示:
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>

class mymutex : public std::mutex {
public:
void lock() {
std::mutex::lock();
std::cout << "mutex " << _i << " locked" << std::endl;
}
mymutex(int i): _i(i){}
bool try_lock() {
bool res = std::mutex::try_lock();
if (res) {
std::cout << "mutex " << _i << " try locked" << std::endl;
}
return res;
}
void unlock() {
std::mutex::unlock();
std::cout << "mutex " << _i << " unlocked" << std::endl;
}
private:
int _i;
};

class Speaking {
private:
int a;
mymutex my1;
mymutex my2;
mymutex my3;

public:
Speaking() : a(0), my1(1), my2(2), my3(3){};
~Speaking() = default;
void speak_without_lock();
void speak_with_three_lock();
};

void Speaking::speak_without_lock() {
std::cout << std::this_thread::get_id() << ": " << a << std::endl;
a++;
}

void Speaking::speak_with_three_lock()
{
std::scoped_lock<mymutex, mymutex, mymutex> scoped(my1, my2, my3);
speak_without_lock();
}

int main() {
Speaking s;

s.speak_with_three_lock();

return 0;
}
mutex 1 locked
mutex 2 try locked
mutex 3 try locked
1: 0
mutex 1 unlocked
mutex 2 unlocked
mutex 3 unlocked
那么 cppreference 会出错吗?

最佳答案

我相信 cppreference.com 在这个细节上是不正确的。 C++17 说:

~scoped_lock();

Effects: For all i in [0, sizeof...(MutexTypes)), get(pm).unlock()


这意味着锁的释放顺序与它们被释放的顺序相同。
请注意,为了防止死锁,不需要以与获取它们相反的顺序释放锁——只需要始终以相同的顺序获取它们。

关于c++ - 如何理解scoped_lock的析构函数?cppreference是不是出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69065454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com