Python, counter atomic increment

Most likely with an threading.Lock around any usage of that value. There's no atomic modification in Python unless you use pypy (if you do, have a look at __pypy__.thread.atomic in stm version).


itertools.count returns an iterator which will perform the equivalent to getAndIncrement() on each iteration.

Example:

import itertools
cont = itertools.count()
value = next(cont)

This will perform the same function, although its not lockless as the name 'AtomicInteger' would imply.

Note other methods are also not strictly lockless -- they rely on the GIL and are not portable between python interpreters.

class AtomicInteger():
    def __init__(self, value=0):
        self._value = int(value)
        self._lock = threading.Lock()
        
    def inc(self, d=1):
        with self._lock:
            self._value += int(d)
            return self._value

    def dec(self, d=1):
        return self.inc(-d)    

    @property
    def value(self):
        with self._lock:
            return self._value

    @value.setter
    def value(self, v):
        with self._lock:
            self._value = int(v)
            return self._value

Using the atomics library, the same could would be written in Python as:

import atomics


a = atomics.atomic(width=4, atype=atomics.INT)

value = a.fetch_inc()

This method is strictly lock-free.

Note: I am the author of this library

Tags:

Python