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

查看:84
本文介绍了在不同的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值不同,因此现在读取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.

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

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天全站免登陆