Simple thread-safe counter?

Skip Montanaro skip at pobox.com
Sat Apr 2 00:03:24 EST 2005


    Paul> I'd like to have a function (or other callable object) that
    Paul> returns 0, 1, 2, etc. on repeated calls.
    ...
    Paul> There should never be any possibility of any number getting
    Paul> returned twice, or getting skipped over, even if f is being called
    Paul> from multiple threads.

How about (untested):

    import Queue

    counter = Queue.Queue()
    counter.put(0)
    def f():
        i = counter.get()
        counter.put(i+1)
        return i

Obviously, if you want multiple counters for some reason a little
information hiding with a class would help (also untested):

    import Queue

    class Counter:
        def __init__(self, start=0):
            self.counter = Queue.Queue()
            self.counter.put(start)

        def __call__(self):
            i = self.counter.get()
            self.counter.put(i+1)
            return i

Skip



More information about the Python-list mailing list