[英]Will recursive_mutex deadlock when locked by 2 threads?
std::recursive_mutex won't deadlock when the same thread locks it multiple times. 当同一线程多次将其锁定时,std :: recursive_mutex不会死锁。
Will it deadlock when multiple threads lock it multiple times? 当多个线程多次锁定它时,它将死锁吗?
Will it deadlock when multiple threads lock it multiple times?
当多个线程多次锁定它时,它将死锁吗?
That cannot happen. 那不可能发生。
By definition a mutex is locked by at most one thread. 根据定义 , 互斥锁最多由一个线程锁定。 And a
std::recursive_mutex
is some kind of mutex. 而且
std::recursive_mutex
是某种互斥体。 Otherwise it does not comply to its goal of mutual exclusion , since it should be some kind of Mutex concept . 否则,它不符合互斥的目标,因为它应该是某种Mutex概念 。
So another thread is not even allowed to lock it a single time. 因此,甚至不允许另一个线程将其锁定一次。 When it does, that other thread stays blocked (till the lock is released - as many times as it was recursively locked).
当这样做时,其他线程保持阻塞状态(直到锁释放-递归锁定的次数)。
FYI, here is a simplistic implementation of a recursive mutex: 仅供参考,这是递归互斥的简单实现:
static const std::thread_id NO_THREAD;
class recursive_mutex {
public:
void lock() {
auto me = std::this_thread::get_id();
if (owner != me) {
mtx.lock();
owner = me;
assert(count == 0);
}
count++;
}
void unlock() {
auto me = std::this_thread::get_id();
assert(owner == me);
assert(count > 0);
count--;
if (count == 0) {
owner = NO_THREAD;
mtx.unlock();
}
}
private:
std::mutex mtx;
std::thread::id owner;
unsigned count{0};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.