Can I atomically increment a 16-bit counter on x86 / x86_64?

I want to save memory by converting an existing 32 bit counter to a 16 bit counter. This counter is incremented / decremented atomically. If I do this:

  • What instructions am I using for atom_inc (uint16_t x) on x86 / x86_64?
  • Is this reliable on x86 / x86_64 multiprocessor machines?
  • Is there a performance penalty for any of these architectures for doing this?
  • If yes for (3), what is the expected performance score?

Thanks for your comments!

+2


source to share


4 answers


Here's one that uses GCC builds as an alternative to Steve Delphi:

uint16_t atomic_inc(uint16_t volatile* ptr)
{
    uint16_t value(1);
    __asm__("lock xadd %w0, %w1" : "+r" (value) : "m" (*ptr));
    return ++value;
}

      



Change 1 from -1 and ++

to --

, to decrease.

+4


source


Here is a Delphi function that works:

function LockedInc( var Target :WORD ) :WORD;
asm
        mov     ecx, eax
        mov     ax, 1
   Lock xadd    [ecx], ax
        Inc     eax
end;

      



I think you could convert it to whatever language you need.

+3


source


The easiest way to do atomic augmentation is as follows (this is inline ASM):

asm
  lock inc dword ptr Counter;
end;

      

where J is an integer. This will directly increment the counter in memory.

I've tested this with brute force and it works 100%.

0


source


To answer the other three questions:

  • Could not find required list starting with 2
  • Yes, it is reliable in a multiprocessor environment
  • Yes, there is a performance limitation
  • The "lock" prefix blocks the buses not only for the processor, but for any external equipment that might want to access the bus via DMA (mass storage, graphics ...). Thus, it is slow, typically ~ 100 clock cycles, but it can be more expensive. But if you have "megabytes" of counters, most likely you will run into a cache miss, in which case you will have to wait about 100 hours anyway (memory access time), in case of page skips there are several hundred, so the overhead blocking costs may not matter.
-1


source







All Articles