Python - 全球反击

时间:2012-09-18 14:55:52

标签: python

我递归地生成了一些对象,这些对象需要一个连续的唯一id。我怎样才能保证(最简单)python 2.7中的同步。

iid = 1

def next_id():
    iid += 1
    return iid

def process():
    # .. do something
    id = next_id()

3 个答案:

答案 0 :(得分:13)

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()本质上是一个无限生成值的生成器。

答案 1 :(得分:8)

使用mutex

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

答案 2 :(得分:0)

你在考虑这种事情:

 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)