Python - 全球反击

bsr*_*bsr 2 python

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

iid = 1

def next_id():
    iid += 1
    return iid

def process():
    # .. do something
    id = next_id()
Run Code Online (Sandbox Code Playgroud)

glg*_*lgl 13

from itertools import count
iid = count()

print next(iid) # 0
print next(iid) # 1
print next(iid) # 2
Run Code Online (Sandbox Code Playgroud)

等等

new_iid = count(10)
print next(new_iid) # 10
print next(new_iid) # 11
print next(new_iid) # 12
Run Code Online (Sandbox Code Playgroud)

从0开始的其他值开始.

count() 本质上是一个无限产生价值的发电机.

  • @Claudiu阅读关于这个问题的评论,它不需要. (2认同)

Cla*_*diu 10

使用互斥锁:

import threading
iid = 1
iid_lock = threading.Lock()

def next_id():
    global iid
    with iid_lock:
        result = iid
        iid += 1
    return result
Run Code Online (Sandbox Code Playgroud)

您可能希望隐藏类中的内部:

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
Run Code Online (Sandbox Code Playgroud)

编辑:基于评论,似乎你没有使用线程.这意味着您根本不需要锁定机制.你最初编写的内容就足够了,尽管你需要global关键字来使全局变量变为可变:

iid = 1
def next_id():
    global iid
    res = iid
    iid += 1
    return res
Run Code Online (Sandbox Code Playgroud)