Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An atomic, thread-safe incrementing counter for Python
"""An atomic, thread-safe incrementing counter."""
import threading
class AtomicCounter:
"""An atomic, thread-safe incrementing counter.
>>> counter = AtomicCounter()
>>> counter.increment()
>>> counter.increment(4)
>>> counter = AtomicCounter(42.5)
>>> counter.value
>>> counter.increment(0.5)
>>> counter = AtomicCounter()
>>> def incrementor():
... for i in range(100000):
... counter.increment()
>>> threads = []
>>> for i in range(4):
... thread = threading.Thread(target=incrementor)
... thread.start()
... threads.append(thread)
>>> for thread in threads:
... thread.join()
>>> counter.value
def __init__(self, initial=0):
"""Initialize a new atomic counter to given initial value (default 0)."""
self.value = initial
self._lock = threading.Lock()
def increment(self, num=1):
"""Atomically increment the counter by num (default 1) and return the
new value.
with self._lock:
self.value += num
return self.value
if __name__ == '__main__':
import doctest

This comment has been minimized.

Copy link

JustinDylan commented Aug 6, 2018

Thank you for this!!!!! Its saved my bacon, can you tell me how I would include this into a program running 4 threads? these are in order pulse counter, write to storage, send via wifi and monitor battery. These work individually and together apart from the counter, that breaks it! Thank you in advance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.