C++ 中的指针赋值是原子的吗?

发布于 2024-12-27 18:40:59 字数 37 浏览 3 评论 0原文

我实际上听到过两种说法。我怀疑他们不是,但我想解决这个话题。

I've actually heard claims both ways. I suspect they are not, but I wanted to get the topic settled.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

探春 2025-01-03 18:41:00

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.

守护在此方 2025-01-03 18:40:59

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 official boost::atomic<T*>, gccs atomic intrinsics or windows Interlocked*) or wrap all accesses to that pointer in mutexes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文