Skip to content

cpu-memory-model #16

Description

@katsusan

1. summary

When instructions refer to different memory locations, with regards to loads/reads from memory and stores/writes to memory there are 4 possible issues:

  • writes can be reordered ahead of other reads
  • writes can be reordered ahead of other writes
  • reads can be reordered ahead of other reads
  • reads can be reordered ahead of other writes

x86架构下只有最后一种情况会发生,我们称之为strong memory model。
举个例子,假设x和y初始值均为0,有两个线程分别执行下面每组指令:

// thread 1
mov [x],1   ;     向地址x写入1  
mov eax,[y] ;   从地址y读取到eax

// thread 2
mov [y],1   ;     向地址y写入1  
mov ebx,[x] ;   从地址x读取到ebx

在x86下eax和ebx可能的状态中有均为0的组合,按照常规逻辑由于读取x和y时至少有一组是赋值之后执行的,
所以必定发生了reorder。每组线程写和读的地址又不一样,所以cpu难以判定dependency关系而决定不重排。

而像ARM、PowerPC它们上述4种情况都可能会发生,这种称之为weak memory model。

2. TSO model

Another way to be able to predict the x86 processor behaviour is to have a model where each hardware thread has a FIFO buffer for writes, while reads are not immediate, not buffered. When reading a memory location, it is first looked up in the FIFO buffer for writes.

image

x86下每个hardware thread有一个用于store的FIFO buffer,但读不会有缓冲,读的时候会先查询store buffer。
这种称之为 total store ordering
对于互斥的内存访问时需要设置一个全局锁global lock,比如lock指令flush write buffer到内存。

image

refer:
http://bajamircea.github.io/coding/cpp/2019/10/25/cpu-memory-model.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions