Simple thread-safe counter?

Paul Rubin http
Sat Apr 2 00:13:11 EST 2005


Tim Peters <tim.peters at gmail.com> writes:
> The GIL is your friend here:
> 
>     import itertools
>     f = itertools.count().next

Thanks, I was hoping something like this would work but was not sure I
could rely on it.

> 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.

Xrange, of course :).  I don't need to exceed the size of a short int,
so either of these should work fine.  I wonder what measures the Pypy
implementers will take (if any) to make sure these things keep
working, but for now I won't worry about it.

Out of interest, are the above guaranteed to work under Jython?  What
I'm doing right now is a short-term thing that will only have to run
under CPython, but I like to do things the right way when I can.



More information about the Python-list mailing list