Simple thread-safe counter?

Artie Gold artiegold at austin.rr.com
Sat Apr 2 02:42:50 EST 2005


Skip Montanaro wrote:
>     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()
I think you need:
           i = counter.get(True)
for this to work; otherwise a race condition would raise an exception.
>         counter.put(i+1)
>         return i

[snip]

This is, of course dependent upon counter.get() being guaranteed to be 
thread safe. (I haven't found anything in the docs specifically relating 
to that. Perhaps it's implicit?)

Thanks,
--ag

-- 
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays



More information about the Python-list mailing list