memcpy() 相邻内存区域的安全性

发布于 2024-10-12 06:02:30 字数 441 浏览 3 评论 0原文

我最近问了一个关于使用 volatile 的问题并被要求阅读一些来自英特尔和其他公司的信息非常丰富的文章,讨论内存屏障及其用途。读完这些文章后,我变得相当偏执。

我有一台 64 位机器。从多个线程 memcpy 到相邻的、不重叠的内存区域是否安全?例如,假设我有一个缓冲区:

char buff[10];

一个线程 memcpy 到前 5 个字节,而另一个线程复制到最后 5 个字节,是否总是安全?

我的直觉反应(和一些简单的测试)表明这是完全安全的,但我一直无法在任何地方找到可以完全说服我的文档。

I recently asked a question on using volatile and was directed to read some very informative articles from Intel and others discussing memory barriers and their uses. After reading these articles I have become quite paranoid though.

I have a 64-bit machine. Is it safe to memcpy into adjacent, non-overlapping regions of memory from multiple threads? For example, say I have a buffer:

char buff[10];

Is it always safe for one thread to memcpy into the first 5 bytes while a second thread copies into the last 5 bytes?

My gut reaction (and some simple tests) indicate that this is completely safe, but I have been unable to find documentation anywhere that can completely convince me.

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

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

发布评论

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

评论(4

三岁铭 2024-10-19 06:02:30

安全,是的。高性能,不,至少在这个有限的例子中。请记住,一个高速缓存行不能同时位于两个内核中。您将强制核心 A 在核心 B 写入缓冲区时等待,然后在内存传输时等待,然后写入。多核内存副本的大小应该非常大,以避免这种影响。

Safe, yes. Performant, no- in this limited example, at least. Remember that one cache line cannot be in two cores at once. You will force core A to wait while core B writes to the buffer, and then wait while the memory is transferred, and then write to it. Multi-core memory copies should be very large in size to avoid this effect.

束缚m 2024-10-19 06:02:30

是的,它完全安全,对内存总线的访问串行化是在硬件中完成的。

Yes, it completely safe, serialization of access to the memory bus is done in hardware.

葬花如无物 2024-10-19 06:02:30

只要 memcpy 的每个实例都认为它只写入缓冲区的其部分,那么它就是完全安全的。 C++ 中任何形式的数组分配都是非常低级的;它是为程序分配适当大小的连续存储块,并且数组作为除指针之外的任何对象而存在只是一种幻觉。给 memcpy 数组不重叠的范围,它无法知道它们不仅仅是两个完全独立的数组,只是碰巧彼此相邻。写入不会干扰。

As long as each instance of memcpy believes it is writing into only its part of the buffer, it is completely safe. Array allocations of any form in C++ are very low-level; it is a contiguous block of storage allocated at the appropriate size for the program, and the array as an object that exists as anything other than a pointer is simply an illusion. Give memcpy non-overlapping ranges of the array, and it has no way of knowing that they aren't simply two completely separate arrays that just happen to be adjacent to each other. The writes won't interfere.

请别遗忘我 2024-10-19 06:02:30

是的,这与任何类型的“发生在订购前”完全无关。它只是复制字节。

Yes this is totally unrelated to any kind of happens-before ordering. its just copying bytes around.

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