问题
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