Python - Global counter


I am recursively generating few objects, which need a contiguous, unique id. How can I guarantee (easiest) the synchronization in python 2.7.

iid = 1

def next_id():
    iid += 1
    return iid

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

Answers:


Use a mutex:

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

def next_id():
    global iid
    with iid_lock:
        result = iid
        iid += 1
    return result

You might like to hide the internals in a class:

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

EDIT: Based on the comments, it seems like you're not using threads. This means you don't need the locking mechanism at all. What you initially wrote would be sufficient, though you need the global keyword to make the global variable mutable:

iid = 1
def next_id():
    global iid
    res = iid
    iid += 1
    return res