当线程被调度在不同的 CPU 内核上时,预期的内存语义(例如写入后读取)会发生什么情况? [英] What happens to expected memory semantics (such as read after write) when a thread is scheduled on a different CPU core?

查看:20
本文介绍了当线程被调度在不同的 CPU 内核上时,预期的内存语义(例如写入后读取)会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单线程中的代码具有一定的内存保证,例如先写后读(即,将一些值写入内存位置,然后将其读回应该给出您写入的值).

Code within a single thread has certain memory guarantees, such as read after write (i.e. writing some value to a memory location, then reading it back should give the value you wrote).

如果线程被重新调度以在不同的 CPU 内核上执行,这种内存保证会发生什么情况?假设一个线程将 10 写入内存位置 X,然后被重新调度到不同的核心.该内核的 L1 缓存可能具有不同的 X 值(来自之前在该内核上执行的另一个线程),因此现在读取 X 不会像线程预期的那样返回 10.当线程被安排在不同的核心上时,是否会发生一些 L1 缓存同步?

What happens to such memory guarantees if a thread is rescheduled to execute on a different CPU core? Say a thread writes 10 to memory location X, then gets rescheduled to a different core. That core's L1 cache might have a different value for X (from another thread that was executing on that core previously), so now a read of X wouldn't return 10 as the thread expects. Is there some L1 cache synchronization that occurs when a thread is scheduled on a different core?

推荐答案

在这种情况下,所有需要的是,在第一个处理器上执行的写入在进程开始在第二个处理器上执行之前变得全局可见.在 Intel 64 架构中,这是通过在操作系统用来将进程从一个内核传输到另一个内核的代码中包含一条或多条具有内存栅栏语义的指令来实现的.来自 Linux 内核的示例:

All that is required in this case is that the writes performed while on the first processor become globally visible before the process begins executing on the second processor. In the Intel 64 architecture this is accomplished by including one or more instructions with memory fence semantics in the code that the OS uses to transfer the process from one core to another. An example from the Linux kernel:

/*
 * Make previous memory operations globally visible before
 * sending the IPI through x2apic wrmsr. We need a serializing instruction or
 * mfence for this.
 */
static inline void x2apic_wrmsr_fence(void)
{
    asm volatile("mfence" : : : "memory");
}

这确保了原始内核的存储在执行处理器间中断之前全局可见,处理器间中断将启动在新内核上运行的线程.

This ensures that the stores from the original core are globally visible before execution of the inter-processor interrupt that will start the thread running on the new core.

参考:英特尔架构软件开发人员手册第 3 卷第 8.2 和 8.3 节(文档 325384-071,2019 年 10 月).

Reference: Sections 8.2 and 8.3 of Volume 3 of the Intel Architectures Software Developer's Manual (document 325384-071, October 2019).

这篇关于当线程被调度在不同的 CPU 内核上时,预期的内存语义(例如写入后读取)会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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