我递归地生成几个对象,这些对象需要一个连续的、唯一的 id。如何保证(最简单)python 2.7 中的同步。
iid = 1
def next_id():
iid += 1
return iid
def process():
# .. do something
id = next_id()
我递归地生成几个对象,这些对象需要一个连续的、唯一的 id。如何保证(最简单)python 2.7 中的同步。
iid = 1
def next_id():
iid += 1
return iid
def process():
# .. do something
id = next_id()
from itertools import count
iid = count()
print next(iid) # 0
print next(iid) # 1
print next(iid) # 2
etc., and
new_iid = count(10)
print next(new_iid) # 10
print next(new_iid) # 11
print next(new_iid) # 12
for starting at other values than 0.
count()
is essentially a generator which infinitely yields values.
使用互斥锁:
import threading
iid = 1
iid_lock = threading.Lock()
def next_id():
global iid
with iid_lock:
result = iid
iid += 1
return result
您可能希望隐藏类中的内部:
class IdGenerator(object):
def __init__(self):
self.cur_id = 1
self.lock = threading.Lock()
def next_id(self):
with self.lock:
result = self.cur_id
self.cur_id += 1
return result
编辑:根据评论,您似乎没有使用线程。这意味着您根本不需要锁定机制。您最初编写的内容就足够了,尽管您需要global
关键字来使全局变量可变:
iid = 1
def next_id():
global iid
res = iid
iid += 1
return res
你在想这样的事情:
class Counter():
def __init__(self):
self.theCount = -1
def __call__(self):
self.theCount += 1
return self.theCount
class BorgCounter():
Borg = {'theCount':-1}
def __init__(self):
self.__dict__ = BorgCounter.Borg
def __call__(self):
self.theCount += 1
return self.theCount
myCount = Counter()
mycount2 = Counter()
assert(myCount()==0)
assert(mycount2()==0)
assert(mycount2()==1)
assert(myCount()==1)
assert(myCount()==2)
myCount = BorgCounter()
mycount2 = BorgCounter()
assert(myCount()==0)
assert(mycount2()==1)
assert(mycount2()==2)
assert(myCount()==3)
assert(myCount()==4)