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.
def __init__(self, initial=0):
self.value = initial
self._lock = threading.Lock()
def increment(self, num=1):
self.value += num
And if you just want a one-off and don't want to write a class, it's like so:
counter_lock = threading.Lock()
counter = 0
counter += 1
value = counter
But it could be this much more obvious code:
counter = threading.AtomicCounter()
value = counter.increment()
Thoughts? Would such a class make a good candidate for the standard library? (API could probably be improved.)