Created
June 3, 2022 07:54
-
-
Save dagoof/629cf5ee12b28bba24456596134d63dc to your computer and use it in GitHub Desktop.
An atomic counter written in go ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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