Skip to content

Instantly share code, notes, and snippets.

@dagoof
Created June 3, 2022 07:54
Show Gist options
  • Save dagoof/629cf5ee12b28bba24456596134d63dc to your computer and use it in GitHub Desktop.
Save dagoof/629cf5ee12b28bba24456596134d63dc to your computer and use it in GitHub Desktop.
An atomic counter written in go ...
type Counter struct {
value int32
mutex sync.Mutex
}
func (c *Counter) Increment() {
defer c.mutex.Unlock()
c.mutex.Lock()
atomic.AddInt32(&c.value, 1)
}
func (c *Counter) Decrement() {
defer c.mutex.Unlock()
c.mutex.Lock()
atomic.AddInt32(&c.value, -1)
}
func (c *Counter) Value() int32 {
defer c.mutex.Unlock()
c.mutex.Lock()
return atomic.LoadInt32(&c.value)
}
func (c *Counter) Reset() {
defer c.mutex.Unlock()
c.mutex.Lock()
atomic.StoreInt32(&c.value, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment