Do we need an mfence in the unlock() function of Peterson's lock on x86?

微笑、不失礼 提交于 2019-12-08 10:50:39

问题


Peterson's lock code taken from (german) wikipedia:

# define FALSE 0
# define TRUE 1
# define N 2 

int turn; 
int interested[N]; 

void enter_region(int process)
{
  int other; 
  other = 1 - process; 
  interested[process] = TRUE; 
  turn = other;

  while (interested[other] == TRUE && turn == other) ; 
}

void leave_region(int process)  
{
  interested[process] = FALSE;  
}

Can somebody think of an example where a bug is happening without an mfence in the leave_region function?

N.B.: I know for sure that a mfence is required in the enter_region function.


回答1:


Sure. It doesn't require any particularly unusual situation.

Suppose that a computation is performed in the CR, with the final action being to store the result to memory. Suppose further that soon after the CR, another thread reads the target memory with the purpose of obtaining the computation result. The read must not be reordered with the write else the wrong value will be obtained. To avoid that, an mfence (or other instruction that serves as a memory barrier) is required when you leave the CR.



来源:https://stackoverflow.com/questions/28306064/do-we-need-an-mfence-in-the-unlock-function-of-petersons-lock-on-x86

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!