我是否需要在“p = tmp”之前插入栅栏以避免内存重新排序?由于从线程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/