threading id generator ?

Diez B. Roggisch nospam-deets at web.de
Thu Feb 19 08:03:22 EST 2004


> which locking semantic I must use to implement a shared generator in a
> thread ?
> 
> thanks in advance :)

You could try something like this:

class IdGen:
    def __init__(_):
       _.lock = threading.Lock()
       _.id = 0

    def id_gen(_):
        _.lock.aqcuire()
        new_id = _.id
        _.id += 1
        lock.release()
        return new_id


An instance of IdGen you could store in a global variable. Or you make it a
singleton. Or you pass one instance around for all your threading-objects.
Or you make _.id and _.lock class-variables, and inherit all your
threading-objects from IdGen. Or you make it a module.... and so on :)

--
Regards,

Diez B. Roggisch




More information about the Python-list mailing list