C++ 如何多次锁定互斥锁?
例如:C++ 如何多次锁定互斥锁?,c++,C++,例如: std::mutex g_mutex; void Function2() { std::lock_guard<std::mutex> lock(g_mutex); //do something not thread safe printf("in function2: thread: 0x%08X\n", std::this_thread::get_id().hash()); } void Function1() { std::loc
std::mutex g_mutex;
void Function2()
{
std::lock_guard<std::mutex> lock(g_mutex);
//do something not thread safe
printf("in function2: thread: 0x%08X\n", 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%08X\n", std::this_thread::get_id().hash());
Function2();
}
int main()
{
std::thread t1([](){
Function1();
});
t1.join();
getchar();
return 0;
}
std::mutex g_mutex;
无效函数2()
{
std::锁和保护锁(g\U互斥);
//做一些不安全的事情
printf(“在函数2中:线程:0x%08X\n”,std::this_thread::get_id().hash());
}
无效函数1()
{
std::锁和保护锁(g\U互斥);
//做一些不安全的事情
printf(“在函数1中:线程:0x%08X\n”,std::this_thread::get_id().hash());
函数2();
}
int main()
{
std::线程t1([])(){
功能1();
});
t1.join();
getchar();
返回0;
}
我想通过锁定一个互斥锁使Function1和Function2线程安全,
但它会抛出运行时错误:
已调用R6010-abord()
是否可以只使用一个互斥锁来实现这一点?我不想创建另一个互斥体,有递归互斥体这样的东西,但有人告诉我,它们被认为是有问题的。用于讨论。我将使用未锁定版本的函数,并通过在结构/类中将其设为私有来隐藏它:
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%08X\n", std::this_thread::get_id().hash());
f2_i();
}
private:
static void f2_i()
{
//do something not thread safe
printf("in function2: thread: 0x%08X\n", std::this_thread::get_id().hash());
}
};
struct函数{
公众:
静态空隙f2()
{
std::锁紧保护锁(g_mutext);
f2_i();
}
静态空隙f1()
{
std::锁紧保护锁(g_mutext);
//做一些不安全的事情
printf(“在函数1中:线程:0x%08X\n”,std::this_thread::get_id().hash());
f2_i();
}
私人:
静态空隙f2_i()
{
//做一些不安全的事情
printf(“在函数2中:线程:0x%08X\n”,std::this_thread::get_id().hash());
}
};
需要多次锁定同一个互斥锁通常是一个糟糕设计的标志
重新设计以避免多次锁定同一互斥锁,或者使用递归互斥锁。显而易见的解决方案是将需要保护的代码放在单独的块中,这样锁定的范围将在完成后过期。锁应尽可能少且短。如果您正在调用另一个需要锁定同一互斥锁的函数,则必须先将其解锁。这就是(正常)互斥体的设计方式。