<div dir="ltr"><div>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.</div><div><br></div><div>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.</div><div><br></div><div>The fact that I and many other folks have implemented such things makes me wonder if it should be in the standard library.</div><div><br></div><div>It's pretty simple to implement, basically the handful of lines of code below (full version on GitHub Gist at <a href="https://gist.github.com/benhoyt/8c8a8d62debe8e5aa5340373f9c509c7">https://gist.github.com/benhoyt/8c8a8d62debe8e5aa5340373f9c509c7</a>):</div><div><br></div><div><div>    import threading</div><div><br></div><div>    class AtomicCounter:</div><div>        def __init__(self, initial=0):</div><div>            self.value = initial</div><div>            self._lock = threading.Lock()</div><div><br></div><div>        def increment(self, num=1):</div><div>            with self._lock:</div><div>                self.value += num</div><div>                return self.value</div><div><br></div><div>And if you just want a one-off and don't want to write a class, it's like so:</div><div><br></div><div>    import threading</div><div><br></div><div>    counter_lock = threading.Lock()</div><div>    counter = 0</div><div><br></div><div>    with counter_lock:</div><div>        counter += 1</div><div>        value = counter</div><div>    print(value)</div></div><div><br></div><div>But it could be this much more obvious code:</div><div><br></div><div>    import threading</div><div>    counter = threading.AtomicCounter()</div><div>    value = counter.increment()</div><div>    print(value)</div><div><br></div><div>Thoughts? Would such a class make a good candidate for the standard library? (API could probably be improved.)</div><div><br></div><div>-Ben</div><div><br></div></div>