如何多次锁定互斥锁
how to lock a mutex multiple times?
例如:
std::mutex g_mutex;
void Function2()
{
std::lock_guard<std::mutex> lock(g_mutex);
//do something not thread safe
printf("in function2: thread: 0x%08Xn", std::this_thread::get_id().hash());
}
void Function1()
{
std::lock_guard<std::mutex> lock(g_mutex);
//do something not thread safe
printf("in function1: thread: 0x%08Xn", std::this_thread::get_id().hash());
Function2();
}
int main()
{
std::thread t1([](){
Function1();
});
t1.join();
getchar();
return 0;
}
我想通过锁定一个互斥锁来使Function1和Function2线程安全,但是会抛出运行时错误:
R6010 - board()已被调用
有可能只使用一个互斥锁吗?我不想再创建一个互斥对象
我将使用该函数的未锁定版本,并通过在struct/class中将其设置为私有来隐藏它:
struct Functions {
public:
static void f2()
{
std::lock_guard<std::mutex> lock(g_mutext);
f2_i();
}
static void f1()
{
std::lock_guard<std::mutex> lock(g_mutext);
//do something not thread safe
printf("in function1: thread: 0x%08Xn", std::this_thread::get_id().hash());
f2_i();
}
private:
static void f2_i()
{
//do something not thread safe
printf("in function2: thread: 0x%08Xn", std::this_thread::get_id().hash());
}
};
需要多次锁定同一个互斥锁通常是糟糕设计的标志。
要么重新设计以避免多次锁定同一个互斥锁,要么使用递归互斥锁
确实存在递归互斥锁,但我被告知它们是有问题的。https://groups.google.com/forum/?hl=en#!topic/comp.programming.threads/tcrTKnfP8HI%5B51-75-false%5D和递归锁(互斥锁)与非递归锁(互斥锁)的讨论
相关文章:
- 在c++中多次调用方法
- 在多次运行中获得一致的callgrind输出
- 在 openGL 中多次绑定缓冲区
- 如何多次询问来自QML对话框的输入?
- 如何使用运算符在同一行中多次调用函数
- C++如何在多次执行后记住过去给出的输入
- 在C++中多次调用相同的 lambda
- 如何使用多次 memcpy 转换回 std::vector<unsigned char>?
- 多次实现成员功能
- 函数被多次调用
- 在 c++ 中多次更改字符串列表
- 当要访问的对象被多次封装时,如何正确使用setter
- 如果包含映射的静态库与可执行文件和动态库链接,静态映射(变量)是否会被多次释放?
- 如何在派生构造函数中多次构造基类
- 多次拨打ruby_init和ruby_finalize
- 如何多次使用Clang LibTooling
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- 如何多次锁定互斥锁
- 无锁定作业队列(多次读/写)-请求审查