Python atomic counter

Do you need a thread-safe atomic counter in Python? Use itertools.count():

>>> from itertools import count
>>> counter = count()
>>> next(counter)
0
>>> next(counter)
1
>>> next(counter)
2

I found this in the decorator package, labelled Atomic get-and-increment provided by the GIL. So simple! So cool!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.