Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

atomic increment

10 views
Skip to first unread message

Alexandru Mosoi

unread,
Aug 26, 2008, 11:18:00 AM8/26/08
to
how can i do an atomic read+increment? something like

with lock:
old = atomic_int
atomic_int += 1

but in one operation

Diez B. Roggisch

unread,
Aug 26, 2008, 11:56:13 AM8/26/08
to
Alexandru Mosoi wrote:

As above - the lock (under the assumption that it is actually a
threading.Lock) will ensure that.

Diez

Frank Millman

unread,
Aug 27, 2008, 1:09:52 AM8/27/08
to

Just out of interest, would the following, without a lock, be safe?

old, atomic_int = atomic_int, atomic_int+1

Frank Millman

Paul Rubin

unread,
Aug 27, 2008, 1:39:56 AM8/27/08
to
Frank Millman <fr...@chagford.com> writes:
> Just out of interest, would the following, without a lock, be safe?
> old, atomic_int = atomic_int, atomic_int+1

No I don't think so. But I'm told that in CPython, you can say

counter = iter(xrange(10000000)) # some number that exceeds what you'll use
...

atomic_int = counter.next()

and the GIL keeps it safe. When in doubt, use a lock or communicate
with other threads through Queues.

Fredrik Lundh

unread,
Aug 27, 2008, 5:56:47 AM8/27/08
to pytho...@python.org
Frank Millman wrote:

> Just out of interest, would the following, without a lock, be safe?
>
> old, atomic_int = atomic_int, atomic_int+1

nope.

there's some information here (make sure you read the comments):

http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm

and some additional discussion here:

http://mail.python.org/pipermail/python-dev/2006-November/thread.html#69981

</F>

0 new messages