从不同的线程写入相邻的数组元素? [英] Writing to adjacent array elements from different threads?

查看:97
本文介绍了从不同的线程写入相邻的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何现代的通用CPU在其中不安全地从不同线程同时写入数组的相邻元素?我对x86特别感兴趣.您可能会认为编译器没有做任何明显可笑的事情来增加内存粒度,即使它在技术上在标准之内.

Are there any modern, common CPUs where it is unsafe to write to adjacent elements of an array concurrently from different threads? I'm especially interested in x86. You may assume that the compiler doesn't do anything obviously ridiculous to increase memory granularity, even if it's technically within the standard.

我对编写任意大的结构(不仅仅是本机类型)感兴趣.

I'm interested in the case of writing arbitrarily large structs, not just native types.

注意:

请不要提及与错误共享有关的性能问题.我很清楚这些内容,但是对于我的用例来说,它们没有实际意义.我还知道与从读取器以外的线程写入的数据有关的可见性问题.这在我的代码中得到解决.

Please don't mention the performance issues with regard to false sharing. I'm well aware of these, but they're of no practical importance for my use cases. I'm also aware of visibility issues with regard to data written from threads other than the reader. This is addressed in my code.

说明:之所以出现此问题,是因为在某些处理器(例如,旧的DEC Alpha)上,只能以字级别解决内存问题.因此,以非字长(例如单个字节)递增的方式写入内存实际上涉及对要写入的字节加上一些相邻的字节的读取-修改-写入.为了直观地看到这一点,请想一想写的内容.您读入字节或字,对整个内容执行按位运算,然后将整个内容写回.因此,您不能安全地从不同的线程中同时写入相邻位.

Clarification: This issue came up because on some processors (for example, old DEC Alphas) memory could only be addressed at word level. Therefore, writing to memory in non-word size increments (for example, single bytes) actually involved read-modify-write of the byte to be written plus some adjacent bytes under the hood. To visualize this, think about what's involved in writing to a single bit. You read the byte or word in, perform a bitwise operation on the whole thing, then write the whole thing back. Therefore, you can't safely write to adjacent bits concurrently from different threads.

从理论上说,即使完全不需要,编译器也有可能在硬件不需要它时以这种方式实现内存写入. x86可以处理单个字节,因此这基本上不是问题,但是我试图弄清楚是否存在任何奇怪的极端情况.更笼统地说,我想知道从不同线程向数组的相邻元素写入是否仍然是一个实际问题,还是只是一个理论性问题,仅适用于晦涩/古老的硬件和/或真正奇怪的编译器.

It's also theoretically possible, though utterly silly, for a compiler to implement memory writes this way when the hardware doesn't require it. x86 can address single bytes, so it's mostly not an issue, but I'm trying to figure out if there's any weird corner case where it is. More generally, I want to know if writing to adjacent elements of an array from different threads is still a practical issue or mostly just a theoretical one that only applies to obscure/ancient hardware and/or really strange compilers.

另一个这是一个很好的参考,描述了我正在谈论的问题:

Yet another edit: Here's a good reference that describes the issue I'm talking about:

http://my.safaribooksonline.com/book/programming/java/0321246780/threads-and-locks/ch17lev1sec6

推荐答案

是的,绝对可以,写一个跨越CPU缓存行边界的未对齐字不是原子.

Yes, definitely, writing a mis-aligned word that straddles the CPU cache line boundary is not atomic.

这篇关于从不同的线程写入相邻的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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