从多个线程读取 int 安全吗?
我有多个线程读取相同的 int 变量。 并且一个线程正在写入该值。
我不关心比赛条件。
我唯一关心的是同时写入和读取 int 值内存安全吗?
并且不会导致任何应用程序崩溃。
I have multiple threads reading same int variable.
and one thread is writing the value.
I don't care about the race condition.
only my concern is writing and reading int value at same time is memory safe ?
and it will not result in any application crash .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,应该没问题。我可以想象崩溃的唯一方法是如果其中一个线程释放支持该整数的内存。为了获得最佳结果,我还要确保整数在 sizeof(int) 边界处对齐。 (如果没有这种对齐方式,某些 CPU 根本无法访问整数。其他 CPU 为未对齐访问提供较弱的原子性保证。)
Yes, that should be all right. The only way I can envision that crashing is if one of the threads deallocates the memory backing that integer. For best results I would also make sure the integers are aligned at
sizeof(int)
boundaries. (Some CPUs cannot access integers at all without this alignment. Others provide weaker guarantees of atomicity for unaligned access.)是的,在 x86 和 x86-64 上,只要您读取的值正确对齐即可。 32 位
int
,它们需要在 4 字节边界上对齐,以便访问原子 在读取或写入时,几乎总是如此,除非您特意创建未对齐的int
s(例如,通过使用打包结构或通过使用字节缓冲区进行转换/指针算术)。您可能还想将变量声明为
易失性
,以便编译器生成代码,在每次访问变量时从内存中重新获取该变量。这将阻止它进行优化,例如当它可能被另一个线程更改时将其缓存在寄存器中。Yes, on x86 and x86-64, as long as the value you're reading is aligned properly. 32-bit
int
s, they need to be aligned on a 4-byte boundary in order for access to be atomic when reading or writing, which will almost always be the case unless you go out of your way to create unalignedint
s (say, by using a packed structure or by doing casting/pointer arithmetic with byte buffers).You probably also want to declare your variable as
volatile
so that the compiler will generate code that will re-fetch the variable from memory every time it's accessed. That will prevent it from making optimizations such as caching it in a register when it might be altered by another thread.在我所知道的所有 Linux 平台上,对齐 int 的读取和写入都是原子的且安全的。您永远不会读取未写入的值(不会出现单词撕裂)。您永远不会造成故障或崩溃。
On all Linux platforms that I know of, reads and writes of aligned int's are atomic and safe. You will never read a value that wasn't written (no word tearing). You will never cause a fault or crash.