Reputation: 314
Hi I'm new to the gcc's built-in atomic functions. And I'm using the test-and-set
one. You may find the reference here
Here's the question:
I've done 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 to check the assembly instruction of __sync_lock_test_and_set
. I've used:
gcc -S [filename].c
And the result is:
.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 can't find where the test_and_set instruction is...
As you can see, I'm using gcc-4.8.1, and the environment is MAC OSX 10.10(I'm sure that this gcc is not what Apple provides. I've compiled this by myself)
Thanks!
Upvotes: 5
Views: 2676
Reputation: 58782
movl $1, -8(%ebp) # lock = true
movl $1, %eax # true argument
xchgl -8(%ebp), %eax # the test-and-set
It is an atomic exchange, which returns the previous value (that's the test part) and writes 1
into the variable (the set part). This is used to implement mutexes. After the operation the lock will be held by somebody - either the original owner or your code that has just acquired it. That's why it's safe to write a value of 1
. The original value is returned, so you can distinguish between those two events. If the original value was 0
then you got the lock and can proceed, otherwise you need to wait because somebody else has it.
Upvotes: 7