Skip to content

Instantly share code, notes, and snippets.

@technikamateur
Created May 16, 2024 17:23
Show Gist options
  • Save technikamateur/d1a1614596496fde0fe144aefe25e593 to your computer and use it in GitHub Desktop.
Save technikamateur/d1a1614596496fde0fe144aefe25e593 to your computer and use it in GitHub Desktop.
This small example shows how to use cmpxchg in C using inline assembly
#include <stdio.h>
#include <stdint.h>
uint32_t lockin = 0;
uint32_t cmpxchg(uint32_t new, uint32_t old, volatile uint32_t* lock) {
uint32_t result = 0;
asm volatile(
"lock cmpxchg %2,%1\n"
"sete (%3)\n"
: : "a"(old),"m"(*lock),"r"(new),"r"(&result)
: "memory","cc"
);
return result;
}
int main() {
uint32_t result = cmpxchg(1,0,&lockin);
printf("Erg: %d\n", result);
printf("Lock: %d\n", lockin);
uint32_t result2 = cmpxchg(1,0,&lockin);
printf("Erg: %d\n", result2);
printf("Lock: %d\n", lockin);
uint32_t result3 = cmpxchg(2,1,&lockin);
printf("Erg: %d\n", result3);
printf("Lock: %d\n", lockin);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment