To create a thread-safe counter using atomic operations in Golang, you can use the sync/atomic
package.
Here's an example code snippet demonstrating how to create a thread-safe counter:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type Counter struct {
value int64
}
func (c *Counter) Increment() {
atomic.AddInt64(&c.value, 1)
}
func (c *Counter) Decrement() {
atomic.AddInt64(&c.value, -1)
}
func (c *Counter) Value() int64 {
return atomic.LoadInt64(&c.value)
}
func main() {
counter := Counter{}
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
counter.Increment()
wg.Done()
}()
}
wg.Wait()
fmt.Println("Counter value:", counter.Value())
}
In the above code, we have defined a Counter
struct with an int64
value. The Increment
and Decrement
methods use atomic operations AddInt64
to modify the counter's value. The Value
method uses LoadInt64
to retrieve the current counter value.
In the main
function, we create an instance of Counter
, and then launch 100 goroutines, each calling the Increment
method. We use a sync.WaitGroup
to wait for all goroutines to finish before printing the final counter value.
The atomic operations provided by the sync/atomic
package ensure that the counter is safely accessed and modified by multiple goroutines without requiring explicit locks or mutexes.