How to Implement a Thread-Safe Counter in Go

Implement a thread-safe counter in Go by wrapping an integer with a sync.Mutex to lock access during read and write operations.

Use a sync.Mutex to guard access to the counter variable, ensuring only one goroutine modifies it at a time.

package main

import (
	"sync"
)

type Counter struct {
	mu  sync.Mutex
	val int
}

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

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