itertools.count is one of the few atomic constructs available (at least to the extent that the GIL’s protection can be considered atomic), which makes it useful as a shared sequence or counter, however this is hampered by the inability for an observer to access the value without incrementing, at least without tricks: it’s possible to retrieve the current value by either parsing the
repr or using the pickling protocol:
>>> import itertools >>> c = itertools.count() >>> next(c); next(c); next(c) 0 1 2 >>> c count(3) >>> c.__reduce__() (<class 'itertools.count'>, (3,))
A property to access the current value would make for much simpler e.g. task or work counting, without needing to adjust for retrieval updates or the like.
A straight addition would have to be protected by a mutex as it’s not atomic,
a += ? compiling to (more or less)
LOAD a LOAD ? INPLACE_ADD STORE a
with 3 suspention points between the loading and storage of
Add basic atomic constructs (CAS, possibly load and store, maybe even operators like inc/dec/add/sub) to cpython, however it’s not entirely clear to me how that would work without language support, since the atomic constructs would need access to the storage location itself in order to atomically load/store while holding the GIL (or a finer lock if the GIL ends up getting removed).
Mutexes are a lot more expensive in all dimensions: they’re pretty costly, they require more code, and they have a higher semantic overhead as the lock and what it protects are not technically directly linked. Though possibly an other alternative would be to make locks into (optional) containers à la Rust, and maybe add convenience / utility pseudo-atomics.