Files
ostep-code/threads-locks/compare-and-swap.c
Remzi Arpaci-Dusseau 5774f100ce init CAS example
2019-02-28 18:40:59 -06:00

30 lines
732 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <stdio.h>
int global = 0;
char compare_and_swap(int *ptr, int old, int new) {
unsigned char ret;
// Note that sete sets a byte not the word
__asm__ __volatile__ (
" lock\n"
" cmpxchgl %2,%1\n"
" sete %0\n"
: "=q" (ret), "=m" (*ptr)
: "r" (new), "m" (*ptr), "a" (old)
: "memory");
return ret;
}
int main(int argc, char *argv[]) {
printf("before successful cas: %d\n", global);
int success = compare_and_swap(&global, 0, 100);
printf("after successful cas: %d (success: %d)\n", global, success);
printf("before failing cas: %d\n", global);
success = compare_and_swap(&global, 0, 200);
printf("after failing cas: %d (old: %d)\n", global, success);
return 0;
}