我需要在工作方法中对unique_lock :: owns_lock()进行断言,但我不'想要传递unique_lock作为参数,而是将其用作静态变量。但这意味着我不能使用unique_lock来实现其RAII行为。 有这样的代码是否公平:是std :: lock_guard <std :: unique_lock <std::mutex>>有效还是推荐?
namespace
{
std::mutex gMtx;
std::unique_lock<std::mutex> gLock(gMtx, std::defer_lock);
}
void foo()
{
assert(gLock.owns_lock());
// ...
}
void bar()
{
std::lock_guard<std::unique_lock<std::mutex>> lock(gLock);
//...
foo();
//...
}
想法?
这样做似乎有效。 的#include “stdafx.h中” #包括使用命名空间std 的#include 的#include 的#include ; namespace { mutex gMtx; unique_lock gLock(gMtx,defer_lock); } void foo(const string&msg) assert(gLock.owns_lock()); cout << msg << endl; } void bar() { lock_guard > lock(gLock); foo(“bar()”); } int main() { bar(); return 0; } –
asterisc
作为解决方法,您可以将互斥量更改为recursive_mutex,并将其锁定在'foo()'中。 –