diff --git a/abb_egm_client/atomic_counter.py b/abb_egm_client/atomic_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..a78a1dab8a435918a087297dfbc5efd8e09756a3 --- /dev/null +++ b/abb_egm_client/atomic_counter.py @@ -0,0 +1,60 @@ +import threading + + +class AtomicCounter: + """An atomic, thread-safe counter. + + From: + https://gist.github.com/benhoyt/8c8a8d62debe8e5aa5340373f9c509c7#gistcomment-3142969 + + >>> counter = AtomicCounter() + >>> counter.inc() + 1 + >>> counter.inc(num=4) + 5 + >>> counter = AtomicCounter(42.5) + >>> counter.value + 42.5 + >>> counter.inc(num=0.5) + 43.0 + >>> counter = AtomicCounter() + >>> def incrementor(): + ... for i in range(100000): + ... counter.inc() + >>> threads = [] + >>> for i in range(4): + ... thread = threading.Thread(target=incrementor) + ... thread.start() + ... threads.append(thread) + >>> for thread in threads: + ... thread.join() + >>> counter.value + 400000 + """ + + def __init__(self, initial=0): + """Initialize a new atomic counter to given initial value""" + self._value = initial + self._lock = threading.Lock() + + def inc(self, num=1): + """Atomically increment the counter by num and return the new value""" + with self._lock: + self._value += num + return self._value + + def dec(self, num=1): + """Atomically decrement the counter by num and return the new value""" + with self._lock: + self._value -= num + return self._value + + @property + def value(self): + return self._value + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/environment.yml b/environment.yml index df4382de52de5b4a6e882466a24169f23ffad80d..33f2bd3a97508d109c4f6ce8292bd6286c9cb373 100644 --- a/environment.yml +++ b/environment.yml @@ -1,6 +1,7 @@ -name: abb-egm-examples +name: abb-egm-examples1 channels: - conda-forge dependencies: + - python >=3.9, <3.10 - numpy - protobuf diff --git a/pyproject.toml b/pyproject.toml index 9ac9b912aae30d4a63758999e0698edd94e3c2e4..a8df0f8cc4d4a1403f17ee7f4a19d6723bec6aa1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,3 +4,6 @@ requires = [ "wheel", ] build-backend = "setuptools.build_meta" + +[tool.isort] +profile = "black" diff --git a/setup.cfg b/setup.cfg index d267f5d768649409db3bbb5c27d29bc6c4a731b5..d2f3dc6ea1456dcbdb1246d5dfa64d019b5714e4 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,6 +4,16 @@ version = 0.1.0 [options] packages = abb_egm_client -python_requires = >= 3.8 +python_requires = >= 3.9 install_requires = protobuf + +[options.extras_require] +dev = + black + flake8 + isort >= 5.0.0 + +[flake8] +max-line-length = 88 +extend-ignore = E203