I am writting this post in connection to Deep understanding of volatile in Java
public class Main {
private int x;
private volatile int g;
public void actor1(){
x = 1;
g = 1;
}
public void actor2(){
put_on_screen_without_sync(g);
put_on_screen_without_sync(x);
}
}
Now, I am analyzing what JIT generated for above piece of code. From our discussion in my previous post we know that output 1, 0
is impossible because:
write to volatile v
causes that every action a
preceeding v
causes that a
will be visible (will be flushed to memory) before v
will be visible.
.................(I removed not important body of method).....
0x00007f42307d9d5e: c7460c01000000 (1) mov dword ptr [rsi+0ch],1h
;*putfield x
; - package.Main::actor1@2 (line 14)
0x00007f42307d9d65: bf01000000 (2) mov edi,1h
0x00007f42307d9d6a: 897e10 (3) mov dword ptr [rsi+10h],edi
0x00007f42307d9d6d: f083042400 (4) lock add dword ptr [rsp],0h
;*putfield g
; - package.Main::actor1@7 (line 15)
0x00007f42307d9d72: 4883c430 add rsp,30h
0x00007f42307d9d76: 5d pop rbp
0x00007f42307d9d77: 850583535116 test dword ptr [7f4246cef100h],eax
; {poll_return}
0x00007f42307d9d7d: c3 ret
Do I understand correctly that it works because x86 cannot make StoreStore
reordering? If it could it would require additional memory barrier, yes?
EDITED AFTER EXCELLENT @Eugene's answer:
int tmp = i; // volatile load // [LoadStore] // [LoadLoad]
Here, I see what do you mean- it is clear: every action below (after)
volatile read (int tmp = i
) doesn't be reordered.
// [StoreLoad] -- this one int tmp = i; // volatile load // [LoadStore] // [LoadLoad]
Here, you put one more barrier. It ensures us that no action will be reordered with int tmp = i
. But, why it is important? Why I have doubts? From what I know volatile load
guarantees:
Every action after volatile load won't be reordered before volatile load is visible.
I see you write:
There needs to be a sequential consistency
But, I cannot see why sequential consistency is required.
a
? Whatv
? Did you meanx
andg
? – Willettawillettea
is any action abovev
- for example it is an action:x = 1
.v
is a store:g = 1
– Ruffleg = 1
. It seems to be errorneous but it isn't in fact. I just try to understand why. – Ruffle