Implement a struct with methods to safely increment, decrement, and retrieve a counter using sync.Mutex or sync/atomic.
HardProblem Statement
Implement a struct with methods to safely increment, decrement, and retrieve a counter using sync.Mutex or sync/atomic.
Sample Input
Increment(); Get()
Sample Output
100
Limits
Time: 2s · Memory: 256 MB
Code Editor
00:00
package main
import (
"fmt"
"sync"
)
type SafeCounter struct {
// Your code here
}
func main() {
counter := &SafeCounter{}
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
counter.Increment()
wg.Done()
}()
}
wg.Wait()
fmt.Println(counter.Get()) // Expected Output: 100
}
Input
Increment(); Get()
Expected Output
100