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
Python, counter atomic increment
提问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.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).
最有可能threading.Lock
使用该值的任何用法。除非您使用 pypy(如果使用,请查看__pypy__.thread.atomic
stm 版本),否则 Python 中没有原子修改。
回答by Will Manley
itertools.count
returns 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