gpt4 book ai didi

c++ - 来自 std::unique_ptr 的 STL 容器的 find() 线程安全

转载 作者:太空狗 更新时间:2023-10-29 22:58:45 26 4
gpt4 key购买 nike

示例代码。

class Obj
{
public:
void doSome(void)
{
std::cout << "Hello World!" << std::endl;
}
};

std::unordered_map<int, std::unique_ptr<Obj>> map;

// insert -- done with single thread and before find()
map[123] = std::move( std::unique_ptr<Obj>(new Obj) );

// find -- run from multiple threads
auto search = map.find(123); // <=== (Q)
if (search != map.end())
{
search->second->doSome();
}

(问)

如果有多个线程运行带有ma​​p.find(123)//find 部分,线程安全性如何?

ma​​p.find(123) 是否总能在每个线程 中找到obj?只要search->second不分配给别人就可以了?

最佳答案

当多个线程访问同一个变量并且至少其中一个线程写入它时,您就会发生数据竞争。这里不是这种情况,每个人都在读取相同的数据。没关系。不过,还有另一个问题未在此代码中解决:根据数据存储到 map 对象的时间,某些线程可能看不到 map 对象的更新版本。处理此同步问题的最简单方法是在创建任何读取器线程之前设置 map 对象。

关于c++ - 来自 std::unique_ptr 的 STL 容器的 find() 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39660856/

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