Simple thread-safe counter?
Tim Peters
tim.peters at gmail.com
Fri Apr 1 23:59:13 EST 2005
[Paul Rubin]
> 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.
The GIL is your friend here:
import itertools
f = itertools.count().next
A similar thing can be done with xrange. But either way sucks if you
call it often enough to exceed the size of a Python short int
(platform C long). The obvious way with an explicit mutex doesn't
have that problem.
More information about the Python-list
mailing list