The i386 provides a couple of ways to perform an atomic test-and-set. Here, I've provided two different (but mostly equivalent) functions to test-and-set, one that uses the BTS (bit test and set) instruction, and another that uses the XCHG (exchange) instruction.
int testAndSet(unsigned char *b)
{
int result;
asm ("bts $1, %1; sbbl %0, %0":"=r" (result):"m" (*b):"memory");
return result;
}
int testAndSet(unsigned char *addr)
{
unsigned char result = 1;
asm ("xchgb %1, %0":"=m" (*addr),"=r" (result)
:"1" (result) :"memory");
return result;
}