gpt4 book ai didi

c++ - 这个 C++ 指针使用线程安全吗?

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:51 25 4
gpt4 key购买 nike

我是否需要在“p = tmp”之前插入 fence 以避免内存重新排序?由于从线程 2 的角度来看内存重新排序而不使用 fence/atomic/mutex,是否有可能在“(*tmp)[1]=2”之前执行“p=tmp”?

线程 1

extern const std::map<int, int>* p;
auto tmp = new std::map<int, int>;
(*tmp)[1] = 2;
...
(*tmp)[2] = 3;
// do I need insert fence here to make sure above operation on tmp ready before tmp assigned to p?
p = tmp;

线程 2

extern const std::map<int, int>* p; // suppose p initalized with {{1:2}}
assert(p->find(1)->second == 2);

最佳答案

Is it possible "p=tmp" executed before "(*tmp)[1]=2" due to memory reordering from the view of thread 2 without using fence/atomic/mutex?

会发生吗

volatile 应该添加到防止重新排序的事物列表中,但 volatile 仍然不能防止数据竞争

Do I need insert fence before "p = tmp" to avoid memory reordering?

您需要添加同步,但围栏通常不是最优的,是否需要它们是特定于体系结构的。原子会更适合这种情况

#include <atomic>

线程 1

extern std::atomic<const std::map<int, int>*> p;
auto tmp = new std::map<int, int>;
(*tmp)[1] = 2;
...
(*tmp)[2] = 3;
// do I need insert fence here to make sure above operation on tmp ready before tmp assigned to p?
p = tmp;

线程 2

extern std::atomic<const std::map<int, int>*> p; // suppose p initalized with {{1:2}}
assert(p->find(1)->second == 2);

关于c++ - 这个 C++ 指针使用线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51097326/

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