[Python-ideas] Atomic counter / atomic increment
Ben Hoyt
benhoyt at gmail.com
Thu Aug 25 13:31:10 EDT 2016
I had to implement a simple atomic counter the other day to count the total
number of requests processed in a multi-threaded Python web server.
I was doing a demo of "how cool Python is" to my colleagues, and they were
generally wowed, but one of the things that made them do a double-take
(coming mostly from Scala/Java) was that there was no atomic counter in the
standard library.
The fact that I and many other folks have implemented such things makes me
wonder if it should be in the standard library.
It's pretty simple to implement, basically the handful of lines of code
below (full version on GitHub Gist at
https://gist.github.com/benhoyt/8c8a8d62debe8e5aa5340373f9c509c7):
import threading
class AtomicCounter:
def __init__(self, initial=0):
self.value = initial
self._lock = threading.Lock()
def increment(self, num=1):
with self._lock:
self.value += num
return self.value
And if you just want a one-off and don't want to write a class, it's like
so:
import threading
counter_lock = threading.Lock()
counter = 0
with counter_lock:
counter += 1
value = counter
print(value)
But it could be this much more obvious code:
import threading
counter = threading.AtomicCounter()
value = counter.increment()
print(value)
Thoughts? Would such a class make a good candidate for the standard
library? (API could probably be improved.)
-Ben
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160825/3926f12e/attachment.html>
More information about the Python-ideas
mailing list