What is the point of sync/atomic.(Load|Store)Int32 ?

725 views
Skip to first unread message

pgw...@google.com

unread,
Sep 24, 2013, 3:56:32 PM9/24/13
to golan...@googlegroups.com
I understand why the Add... and Compare... methods are useful, but why do we need StoreInt32 and LoadInt32? Aren't they already atomic? Or are we worried about an implementation of Go running on an 8 or 16 bit platform?

P

Ian Lance Taylor

unread,
Sep 24, 2013, 4:29:55 PM9/24/13
to Paul Weiss, golang-nuts
I think you are asking the general question of whether a 32-bit memory
load or store on a 32-bit system is atomic. It depends on what you
mean by atomic. If you mean that following "a = 0; a = 1" no other
processor is going to read a as having a value other than 0 or 1, then
that is generally true.

However, the atomic load and store provide another property. If one
processor executes "a = 1; b = 1" (let's say that a and b are always 0
before) and another processor executes "if b { c = a }" then if the "b
= 1" uses a non-atomic store, or the "if b" uses a non-atomic load,
then it is entirely possible that the second processor will read the
old value of a and set c to 0. That is, using a non-atomic load or
store does not provide any ordering guarantees with regard to other
memory that may have been set by the other processor.

In the current multiprocessor lingo, the sync/atomic package provides
an atomic load-acquire and store-release.

Ian

Dmitry Vyukov

unread,
Sep 24, 2013, 5:07:59 PM9/24/13
to pgw...@google.com, golang-nuts
You almost never care about only atomicity. There is also ordering (as
Ian described) and visibility (loads/stores must be visible to other
goroutines in a finite amount of time, this is not true for non-atomic
loads/store). And there are also data races, which render behavior of
your program undefined.
All the same applies to C/C++ as well.




On Tue, Sep 24, 2013 at 12:56 PM, <pgw...@google.com> wrote:
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
Reply all
Reply to author
Forward
0 new messages