gpt4 book ai didi

c++ - 锁定多个互斥锁

转载 作者:IT老高 更新时间:2023-10-28 22:22:54 24 4
gpt4 key购买 nike

我想知道是否可以同时锁定多个互斥锁,例如:

 Mutex1.Lock();
{
Mutex2.Lock();
{
// Code locked by mutex 1 and 2.
}
Mutex2.Unlock();

// Code locked by mutex 1.
}
Mutex1.Unlock();

这在某些情况下会非常有用。谢谢。

最佳答案

std::lock 似乎就是为此目的而存在的。

Locks the given Lockable objects lock1, lock2, ..., lockn using a deadlock avoidance algorithm to avoid deadlock. The objects are locked by an unspecified series of calls to lock, try_lock, unlock. If a call to lock or unlock results in an exception, unlock is called for any locked objects before rethrowing.

http://en.cppreference.com/w/cpp/thread/lock

关于c++ - 锁定多个互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13483767/

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