是C ++中的指针赋值原子吗? [英] Is pointer assignment atomic in C++?

查看:779
本文介绍了是C ++中的指针赋值原子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上听到过这两种声明。

解决方案

C ++ 03不知道存在的问题的线程,因此原子性的概念对C ++ 03没有多大意义,意味着它不会说任何话。



C ++ 11知道关于线程,但是再次不说任何关于分配指针的原子性。然而,C ++ 11包含 std :: atomic ,它保证是原子的。



请注意,即使写入原始指针在您的平台上是原子的,编译器仍然可以自由移动这个assingment,所以不会真的买你任何东西。



如果你需要写一个在线程之间共享的指针,使用 std :: atomic< T *> (或尚未官方的 boost :: atomic< T *> ,gccs原子内在函数或窗口Interlocked *)或者在互斥体中包装对该指针的所有访问。 / p>

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

解决方案

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.

这篇关于是C ++中的指针赋值原子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆