Python, counter atomic increment

前端 未结 3 1015
庸人自扰
庸人自扰 2020-12-13 09:04

How can I translate the following code from Java to Python?

AtomicInteger cont = new AtomicInteger(0);

int value = cont.getAndIncrement();
3条回答
  •  鱼传尺愫
    2020-12-13 09:38

    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
    

提交回复
热议问题