On Tuesday, 4 October 2016 13:32:03 UTC-4, Ahmed (OneOfOne) W. wrote:
>
> Some of our code uses something like:
>
> type Dummy struct {
> closed int64
> }
>
> func(d *Dummy) IsClosed() bool {
> return atomic.LoadInt64(&d.closed) == 1
> }
>
> func(d *Dummy) Close() error {
> if !atomic.CompareAndSwapInt64(&d.closed, 0, 1) {
> return fmt.Errorf("already closed")
> }
> // other logic
> return nil
> }
>
> IsClosed feels racy to me, is it better to use
> atomic.CompareAndSwap(&d.closed,
> 1, 1) for IsClosed?
>
No. CompareAndSwap(1, 1) atomically checks whether the value is 1, and if
so, sets it to 1, which is of course a no-op, so it's equivalent to the
existing code but slower (and unnecessarily complex).
Be careful though: no matter which one you use, a caller of IsClosed that
observes a true result might assume that the Close operation has completed,
when in fact it has only begun. Depending on what "// other logic" does,
this could be a data race. If so, you should use a mutex to make both
Closed and IsClosed atomic.
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.