有时编写的函数需要在进入该函数之前锁定一个或多个互斥体。如果不指定此要求,则在进入之前可以在不获取相关锁的情况下调用该函数,这可能会带来灾难性的后果。
现在,可以在函数的文档中指定类似这样的内容,但我真的不喜欢那样。
我想在函数的前提条件中指定它(进入函数时断言),但条件应该是什么?
即使 C++11 中的 std::mutex 确实有 has_lock() 函数,仍然无法保证我是拥有锁的人。
最佳答案
如果您真的不想使用递归互斥量并且您的目标是弄清楚当前线程是否持有互斥量而不尝试获取它,那么定义互斥量包装器可能是最简单的解决方案。这是一个疯狂的镜头:
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
template<typename M>
struct mutex_wrapper
{
void lock()
{
m.lock();
lock_guard<mutex> l(idGuardMutex);
threadId = this_thread::get_id();
}
void unlock()
{
lock_guard<mutex> l(idGuardMutex);
threadId = thread::id();
m.unlock();
}
bool is_held_by_current_thread() const
{
lock_guard<mutex> l(idGuardMutex);
return (threadId == this_thread::get_id());
}
private:
mutable mutex idGuardMutex;
thread::id threadId;
M m;
};
下面是一个如何使用它的简单示例:
int main()
{
cout << boolalpha;
mutex_wrapper<mutex> m;
m.lock();
cout << m.is_held_by_current_thread() << endl;
m.unlock();
cout << m.is_held_by_current_thread() << endl;
}
关于c++ - 如何在进入函数之前指定需要什么互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523898/