How can I translate the following code from Java to Python?
AtomicInteger cont = new AtomicInteger(0); int value = cont.getAndIncrement();
There's no atomic modification in Python unless you use pypy (if you do, have a look at __pypy__.
A counter can be made thread-safe using a mutual exclusion (mutex) lock via the threading. Lock class. First, an instance of a lock can be created. Then each time the counter variable is accessed or updated, it can be protected by the lock.
You can make thread-safe calls to print() using a mutex lock such as threading. Lock.
A task performed by a computer is said to be atomic when it is not divisible anymore: it can't be broken into smaller steps. Atomicity is an important property of multithreaded operations: since they are indivisible, there is no way for a thread to slip through an atomic operation concurrently performed by another one.
Most likely with an threading.Lock
around any usage of that value. There's no atomic modification in Python unless you use pypy (if you do, have a look at __pypy__.thread.atomic
in stm version).
itertools.count
returns an iterator which will perform the equivalent to getAndIncrement()
on each iteration.
Example:
import itertools cont = itertools.count() value = next(cont)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With