連続した一意の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
など、および
new_iid = count(10)
print next(new_iid) # 10
print next(new_iid) # 11
print next(new_iid) # 12
0以外の値から開始する場合。
count()
本質的には、値を無限に生成するジェネレータです。
ミューテックスを使用する:
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)