如何将以下代码从Java转换为Python?
AtomicInteger cont = new AtomicInteger(0);
int value = cont.getAndIncrement();
Run Code Online (Sandbox Code Playgroud)
vir*_*tor 31
最有可能threading.Lock使用该值.除非你使用pypy,否则Python中没有原子修改(如果你这样做,请查看__pypy__.thread.atomicstm版本).
Wil*_*ley 22
itertools.count返回一个迭代器,它将getAndIncrement()在每次迭代时执行等效操作.
例:
import itertools
cont = itertools.count()
value = cont.next()
Run Code Online (Sandbox Code Playgroud)
doo*_*pav 18
使用该atomics库,可以用 Python 编写相同的内容,如下所示:
import atomics
a = atomics.atomic(width=4, atype=atomics.INT)
value = a.fetch_inc()
Run Code Online (Sandbox Code Playgroud)
该方法是严格无锁的。
注意:我是这个库的作者
这将执行相同的功能,尽管它不是无锁的,并且暗示“ AtomicInteger”。
请注意,其他方法也不是严格无锁的,它们依赖于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
Run Code Online (Sandbox Code Playgroud)