How to understand atomic test_and_set at assembly level?
Hi I'm new to gcc built-in atomic functions. And I am using test-and-set
one. You can find the link here
Here's the question:
I made this code:
#define bool int
#define true 1
#define false 0
int main() {
bool lock = true;
bool val = __sync_lock_test_and_set(&lock, true);
return 0;
}
What I intend to do is check the build instruction __sync_lock_test_and_set
. I used:
gcc -S [filename].c
And the result:
.file "test_and_set.c"
.file "test_and_set.c"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
subl $16, %esp
movl $1, -8(%ebp)
movl $1, %eax
xchgl -8(%ebp), %eax
movl %eax, -4(%ebp)
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.1"
However, I cannot find where the test_and_set ...
As you can see I am using gcc-4.8.1 and the environment is MAC OSX 10.10 (I'm pretty sure this gcc is not what Apple provides. I compiled this myself)
Thank!
source to share
movl $1, -8(%ebp) # lock = true
movl $1, %eax # true argument
xchgl -8(%ebp), %eax # the test-and-set
It is an atomic exchange that returns the previous value (this is the test part) and writes 1
to a variable (the given part). This is used to implement mutexes. After the operation, the lock will be held by someone - either the original owner or the code that just acquired it. Therefore, it is safe to write the value 1
. The original value is returned, so you can distinguish between the two events. If the original value was 0
, then you got the lock and can continue, otherwise you have to wait because someone else has it.
source to share