Simple thread-safe counter?

Paul Rubin http
Fri Apr 1 23:47:49 EST 2005


I'd like to have a function (or other callable object) that returns
0, 1, 2, etc. on repeated calls.  That is:

    print f()   # prints 0
    print f()   # prints 1
    print f()   # prints 2
    # etc.

There should never be any possibility of any number getting returned
twice, or getting skipped over, even if f is being called from
multiple threads.

What's the simplest and most natural way to do this?  I can think of a
few but am not sure that they work.  And I can think of some ways that
are sure to work, but are messier than I'd like.



More information about the Python-list mailing list