Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this thread-safe with concurrent access?

I have struct with count property need to thread-safe access.

I know it can be done with sync.Mutex or sync.RWMutex. But I am not sure it's ok like this:

type Status struct {
    count uint32

    attr1 string
    attr2 string
}

func (s *Status) Get() uint32 {
    return atomic.LoadUint32(&s.count)
}

func (s *Status) Add(n uint32) {
    atomic.AddUint32(&s.count, n)
}

func (s *Status) Reset(n uint32) {
    atomic.StoreUint32(&s.count, n)
}

Thank you.

Edit:

I'm confused that access field directly s.count is not safe. But atomic.LoadUint32(&s.count) is safe?

like image 762
leiyonglin Avatar asked Oct 18 '22 03:10

leiyonglin


1 Answers

Yes, if only those 3 methods access the count field, your solution is safe to use concurrently from multiple goroutines.

But know that the value returned by Status.Get() may be "outdated" by the time you attempt to use it. E.g.:

s := &Status{}

if s.Get() == 3 {
    fmt.Println(s.Get()) // This may or may not print 3
}

// Or
c := s.Get()
fmt.Println(c == s.Get()) // This may or may not print true

The above example may or may not print 3 and true as the 2nd call to s.Get() might be preceeded by another call to s.Add() in another goroutine.

If you need guarantee that noone else modifies or accesses the value of the Status.count field while you perform further calculations on it, then sync.Mutex or sync.RWMutex is the way to go, as you can hold a lock on the count field while you finish your calculations.

Edit: To answer your edit:

Direct access to s.count is not safe, atomic.LoadUint32(&s.count) is safe. Reason for this is because if goroutine #1 calls s.Add(), and goroutine #2 tries to access s.count, there is no guarantee that goroutine #2 will see changes made by #1. In #2 you may see just a cached version of s.count.

Without explicit synchronization you have no guarantee to observe changes made to a variable in another goroutine. Directly accessing s.count is an unsynchronized access. Use of channels or other synchronization primitives (e.g. sync or sync/atomic packages) ensures serialized access to s.count, so these solutions will always see the current, updated value.

For details, see this article: The Go Memory Model

like image 77
icza Avatar answered Oct 21 '22 05:10

icza