作者:旺小旺大_693 | 来源:互联网 | 2023-08-15 07:45
要以相同顺序获取多个锁多线程在加锁解锁时,可能会出现死锁问题,比如,线程1在加锁mutexA后,继续尝试获取mutexB,而mutexB已经被线程2获取,而线程2在等待获取mute
要以相同顺序获取多个锁
多线程在加锁解锁时,可能会出现死锁问题,比如,
线程 1 在加锁 mutex A 后,继续尝试获取 mutex B,而 mutex B 已经被线程 2 获取,而线程 2 在等待获取 mutex A,mutex B 只有线程 2 获取 mutex A 后才能解锁,
这就导致线程 1 和线程 2 互相等待锁,而这一操作就是死锁情况,容易导致程序挂起。
使用代码模拟死锁场景:
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.
When a scoped_lock
object is created, it attempts to take ownership of the mutexes it is given. When control leaves the scope in which the scoped_lock
object was created, the scoped_lock
is destructed and the mutexes are released. If several mutexes are given, deadlock avoidance algorithm is used as if by std::lock.
或者我们也可以用 std::timed_mutex 来解决这个问题,当超过一定时间后自动释放锁
The timed_mutex
class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.