Sobes.tech
Junior — Middle

How to implement thread-safe increment of a counter inside a structure in Go?

sobes.tech AI

Answer from AI

In Go, to safely increment a counter within a structure when working with multiple goroutines, the sync package is usually used.

The simplest way is to use sync.Mutex to lock access to the counter field:

import "sync"

type Counter struct {
    mu    sync.Mutex
    count int
}

func (c *Counter) Increment() {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.count++
}

func (c *Counter) Value() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.count
}

Another way is to use atomic operations from the sync/atomic package, which allow increasing the value without explicit locking:

import (
    "sync/atomic"
)

type Counter struct {
    count int64
}

func (c *Counter) Increment() {
    atomic.AddInt64(&c.count, 1)
}

func (c *Counter) Value() int64 {
    return atomic.LoadInt64(&c.count)
}

Using atomic operations is preferable if you just need to increment the counter without other complex operations, as it is more efficient in terms of performance.

How to implement thread-safe increment of a counter… - sobes.tech