Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, counter atomic increment

Tags:

python

How can I translate the following code from Java to Python?

AtomicInteger cont = new AtomicInteger(0);  int value = cont.getAndIncrement(); 
like image 712
user2983041 Avatar asked May 08 '14 16:05

user2983041


People also ask

Is Python increment Atomic?

There's no atomic modification in Python unless you use pypy (if you do, have a look at __pypy__.

Is counter thread-safe in Python?

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.

How do you make a Python thread-safe?

You can make thread-safe calls to print() using a mutex lock such as threading. Lock.

Are threads Atomic?

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.


2 Answers

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).

like image 93
viraptor Avatar answered Sep 18 '22 15:09

viraptor


itertools.count returns an iterator which will perform the equivalent to getAndIncrement() on each iteration.

Example:

import itertools cont = itertools.count() value = next(cont) 
like image 24
Will Manley Avatar answered Sep 22 '22 15:09

Will Manley