Skip to content

gbenson.net

Category: Concurrency

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!

gbenson Concurrency, GIL, Python, Snippets Leave a comment Thursday 25th July 2024Thursday 25th July 2024 1 Minute
Proudly powered by WordPress | Theme: Independent Publisher 2 by Raam Dev.