Simple thread-safe counter?

Paul Rubin http
Sat Apr 2 02:54:13 EST 2005


Skip Montanaro <skip at pobox.com> writes:
> How about (untested):
> 
>     import Queue
>     counter = Queue.Queue()
>     counter.put(0)
>     def f():
>         i = counter.get()
>         counter.put(i+1)
>         return i

Hmmm, that's a bit messier than I hoped for, but it looks sure to work.

I think for my immediate requirement, I'm going to use xrange as Tim
suggested.  However, I can't be sure that will work in non-GIL
implementations.



More information about the Python-list mailing list