gpt4 book ai didi

c++ - 在 C++ 中,有没有办法锁定对象本身?

转载 作者:太空狗 更新时间:2023-10-29 21:05:02 25 4
gpt4 key购买 nike

我有一个 STL 映射,我想在多个线程之间进行同步。目前我有...

函数A(修改 map )

void Modify(std::string value)
{
pthread_mutex_lock(&map_mutex);

my_map[value] = value;

pthread_mutex_unlock(&map_mutex);
}

函数 B(读取 map )

std::string Read(std::string key)
{
std::string value;

pthread_mutex_lock(&map_mutex);

std::map<std::string, std::string>::iterator it = my_map.find(key);

pthread_mutex_unlock(&map_mutex);

if(it != my_map.end())
{
return it->second;
}
else
{
return "DNE";
}
}

由于互斥量,这在所有线程中都是同步的。但是,即使它根本没有修改映射,我也必须锁定函数 B 中的互斥量。有没有办法在函数 A 中锁定 my_map 对象本身,而不是在保持线程同步的同时将其锁定在函数 B 中。这样,只要函数 A 没有运行,函数 B 的所有实例/调用都可以继续自由运行?

谢谢

最佳答案

您不只是想锁定容器,您还想锁定对容器的访问,即对其中的任何迭代器或指针。您需要将这些访问权限移至代码的锁定区域。

std::string Read(std::string key)
{
std::string value = "DNE";

pthread_mutex_lock(&map_mutex);

std::map<std::string, std::string>::iterator it = my_map.find(key);
if(it != my_map.end())
{
value = it->second;
}

pthread_mutex_unlock(&map_mutex);

return value;
}

从对象本身内部确实没有切实可行的方法来做到这一点。

关于c++ - 在 C++ 中,有没有办法锁定对象本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10886154/

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