Simple thread-safe counter?
Rob Williscroft
rtw at freenet.co.uk
Sat Apr 2 05:10:43 EST 2005
Tim Peters wrote in news:mailman.1223.1112417955.1799.python-
list at python.org in comp.lang.python:
> [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:
>
Yes but IIUC the GIL is only CPython, will this work with Jython,
IornPython etc ? (*)
> import itertools
> f = itertools.count().next
>
*) I'm either being rhetorical or stupid, not sure which :).
Rob.
--
http://www.victim-prime.dsl.pipex.com/
More information about the Python-list
mailing list