gpt4 book ai didi

c++ - 如何多次锁定互斥锁?

转载 作者:行者123 更新时间:2023-11-30 04:03:05 29 4
gpt4 key购买 nike

例如:

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;
}

我想通过锁定一个互斥锁使 Function1Function2 线程安全,但它抛出运行时错误:

R6010 -abord() has been called

是否可以仅使用一个互斥锁来做到这一点?我不想创建另一个互斥体

最佳答案

我会使用该函数的解锁版本,并通过在结构/类中将其设为私有(private)来隐藏它:

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());
}
};

关于c++ - 如何多次锁定互斥锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698930/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com