C++ 中的指针赋值是原子的吗?
我实际上听到过两种说法。我怀疑他们不是,但我想解决这个话题。
I've actually heard claims both ways. I suspect they are not, but I wanted to get the topic settled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++ 规范没有定义特定的线程行为。根据编译器和平台的不同,指针分配可能是也可能不是原子的。
The C++ norm does not define specific threading behavior. Depending on the compiler and the platform, the pointer assignment may or may not be atomic.
C++03 不知道线程的存在,因此原子性的概念对于 C++03 来说没有多大意义,这意味着它没有提及任何相关内容。
C++11 确实了解线程,但再次没有提及分配指针的原子性。但是 C++11 确实包含
std::atomic
,它保证是原子的。请注意,即使写入原始指针在您的平台上是原子的,编译器仍然可以自由地移动该分配,因此这并不能真正为您带来任何好处。
如果您需要写入在线程之间共享的指针,请使用
std::atomic
(或尚未正式的boost::atomic< /code>、gccs 原子内在函数或 windows Interlocked*)或将对该指针的所有访问包装在互斥体中。
C++03 does not know about the existance of threads, therefore the concept of atomicity doesn't make much sense for C++03, meaning that it doesn't say anything about that.
C++11 does know about threads, but once again doesn't say anything about the atomicity of assigning pointers. However C++11 does contain
std::atomic<T*>
, which is guaranteed to be atomic.Note that even if writing to a raw pointer is atomic on your platform the compiler is still free to move that assingment around, so that doesn't really buy you anything.
If you need to write to a pointer which is shared between threads use either
std::atomic<T*>
(or the not yet officialboost::atomic<T*>
, gccs atomic intrinsics or windows Interlocked*) or wrap all accesses to that pointer in mutexes.