当我编写多线程算法时,我发现一些方法对预期互斥锁的状态很有用。对一些人来说,它已经被锁定,对一些人来说,它还没有。
我想出了如何断言互斥锁是否已经被锁定的方法:
ASSERT(!mutex.try_lock_shared()); // assert if the mutex is not uniquely locked
ASSERT(!mutex.try_lock()); // assert if the mutex is not at least shared locked
问题是我如何才能断言检查互斥锁是否未锁定......从当前线程。例如,如果我这样做
if (mutex.try_lock()) {
mutex.unlock();
} else {
ASSERT(false); // the mutex is locked
}
它显然不时失败,只是因为其他一些线程已将其锁定。