Python,计数器原子增量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23547604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:07:34  来源:igfitidea点击:

Python, counter atomic increment

python

提问by user2983041

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

如何将以下代码从 Java 转换为 Python?

AtomicInteger cont = new AtomicInteger(0);

int value = cont.getAndIncrement();

采纳答案by viraptor

Most likely with an threading.Lockaround 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.atomicin stm version).

最有可能threading.Lock使用该值的任何用法。除非您使用 pypy(如果使用,请查看__pypy__.thread.atomicstm 版本),否则 Python 中没有原子修改。

回答by Will Manley

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

itertools.count返回一个迭代器,它将getAndIncrement()在每次迭代中执行等价于。

Example:

例子:

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

回答by user48956

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

这将执行相同的功能,尽管它不像名称“AtomicInteger”所暗示的那样是无锁的。

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

请注意,其他方法也不是严格无锁的——它们依赖于 GIL,并且在 python 解释器之间不可移植。

class AtomicInteger():
    def __init__(self, value=0):
        self._value = value
        self._lock = threading.Lock()

    def inc(self):
        with self._lock:
            self._value += 1
            return self._value

    def dec(self):
        with self._lock:
            self._value -= 1
            return self._value


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

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