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()
Use a mutex:
You might like to hide the internals in a class:
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
globalkeyword to make the global variable mutable: