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

标签 c++ multithreading memory-model

我是否需要在“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/

相关文章:

仅接受某些类型的 C++ 模板

c++ - 暂停 std::thread 直到函数完成

c - TFTP 中的超时和重新传输问题

带定时器的 Python 线程

c++ - 什么时候字符和 int 连接会导致段错误?

c++ - 氏族库错误 LNK1104 : cannot open file 'clanCore-static-mt-debug.lib' ?

java - cycloBarrier 计算素数

c++ - [[carries_dependency]] 什么意思以及如何实现

c++ - std::atomic 是否提供原子行为,而不管顺序如何?

x86 - 为什么原子 RMW 指令的加载部分不能将较早的存储传递到 TSO(x86) 内存一致性模型中的不相关位置?