![](/img/trans.png)
[英]Is it more efficient to mutex lock a variable multiple times in a code-block, or just lock the whole code-block?
[英]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%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;
}
我想通過鎖定一個互斥鎖使Function1和Function2線程安全,但是會引發運行時錯誤:
R6010 -abord()已被調用
是否可以只使用一個互斥鎖呢? 我不想創建另一個互斥鎖
我將使用該函數的未鎖定版本,並通過將其私有化為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%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());
}
};
通常需要多次鎖定同一個互斥鎖,這表明設計不良。
重新設計以避免多次鎖定同一互斥鎖,或者使用遞歸互斥鎖。
有諸如遞歸互斥這樣的東西,但有人告訴我它們被認為是有問題的。 https://groups.google.com/forum/?hl=zh-CN#!topic/comp.programming.threads/tcrTKnfP8HI%5B51-75-false%5D和遞歸鎖(Mutex)與非遞歸鎖(Mutex)討論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.