递减运算的原子操作实现

递减运算的原子操作实现
long    s;

__declspec(naked) long __stdcall atomic_postdecrement_up(long volatile * )
{
    __asm
    {
        mov eax, -1


            mov ecx, dword ptr [esp + 4]

        mov dword ptr [s], ecx

            xadd dword ptr [ecx], eax

            // Since this is post-decrement, we need do nothing, since the previous
            // value is in eax

            ret 4
    }
}

#include <stdio.h>

int main()
{
    for(long i = 0, j = 10; i < 10; ++i)
    {
        int k;

        k = atomic_postdecrement_up(&j);

        printf("0x%08x\t0x%08x\n", (unsigned long)&j, s);

        printf("%d, %d, %d\n", i, j, k);
    }

    return 0;
}


你可能感兴趣的:(递减运算的原子操作实现)