[Python-ideas] Atomic counter / atomic increment

M.-A. Lemburg mal at egenix.com
Thu Aug 25 14:46:44 EDT 2016


On 25.08.2016 20:10, Ben Hoyt wrote:
>> As long as Python uses a GIL to protect C level function
>> calls, you can use an iterator for this:
>>
>> import itertools
>> x = itertools.count()
>> ...
>> mycount = next(x)
>>
> 
> Yeah, that's a neat hack -- I saw it recommended on StackOverflow, and saw
> it used in the standard library somewhere. I think that's probably okay in
> the *CPython* stdlib, because it's CPython so you know it has the GIL. But
> this wouldn't work in other Python implementations, would it (IronPython
> and Jython don't have a GIL). Or when itertools.count() is implemented in
> pure Python on some system? Seems like it could blow up in someone's face
> when they're least expecting it. I also think using *iter*tools is a pretty
> non-obvious way to get a thread-safe counter.

All true.

Having an implementation in threading which hides away the
details would be nice. On CPython using iterators would
certainly be one of the most efficient ways of doing this.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Aug 25 2016)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...           http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...           http://zope.egenix.com/
________________________________________________________________________

::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/
                      http://www.malemburg.com/



More information about the Python-ideas mailing list