开发者

test&set and test&test&set LOCK implementations in ASM for C

Searching around for some test&set and test&test&set LOCK implementations on ASMx86 (x86 architecture) Assembly to use in my C codes. I don't want implementations in C, but plain assembly.

Please point me to some useful ones.

Thank开发者_Python百科s in advance!


Hare you have a simple implementation of test&set under IA32 x86

//eax = pointer on 32 bit lock variable
//Variable must be 4 byte aligned
//edx = bit test and set number from 0..31
lock    bts     dword ptr [eax], edx
        setnc   al         //al is 1 if bts instruction was successful

And hare you have a simple implementation of looped test&set

//eax = pointer on 32 bit lock variable
//Variable must be 4 byte aligned
//edx = bit test and set number from 0..31
@wait:
        pause                   //CPU hint for waiting in loop
lock    bts     dword ptr [eax], edx
        jc      @wait          //waiting in loop!!!

Remember waiting in loop will freeze the application thread so it is smart to also impement the maximum wait loop time.


Depending on the architecture, you can do this in a single instruction or by disabling interrupts.

80386 and later compatible architectures have the bts instruction which will do test-and-set atomically with the test result in the carry flag. Here is a great explanation of how to use PPC instructions to implement mutexes.

Others require something like:

cli         ;; Clear interrupts flag.
move r0, r1 ;; Copy the value into r0.
ori r1, 1   ;; Set the bit in r1 (r1 holds the value to test-and-set.)
sti         ;; Re-enable interrupts.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜