Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion internal/exercises/catalog.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,15 @@ concepts:
- Close the jobs channel after sending all work to signal workers to finish.
- Use strings.TrimSpace() to clean message strings by removing leading/trailing whitespace.
- Collect exactly len(logs) results to ensure all work is processed.

- slug: 44_atomic_counters
title: Atomic Counters
test_regex: ".*"
hints:
- Use `sync/atomic` package to create and increment atomic counter.
- Launch 10,000 anonymous go routines that simultaneously increment the counter.
- Use WaitGroups to wait for all go routines to finish.


projects:
- slug: 101_text_analyzer
title: Text Analyzer (Easy)
Expand Down
22 changes: 22 additions & 0 deletions internal/exercises/solutions/44_atomic_counters/atomic_counters.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package atomic_counters

import (
"sync"
"sync/atomic"
)

func NoRequestsProcessed() uint64 {

var ops atomic.Uint64
var wg sync.WaitGroup

wg.Add(10_000)
for range 10_000 {
go func() {
defer wg.Done()
ops.Add(1)
}()
}
wg.Wait()
return ops.Load()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package atomic_counters

// TODO: Assume you have to keep track of the number of requests processed
// by an applications to display on a dashboard.
// 1. Launch 10_000 goroutines that increment a counter.
// 2. Wait for all goroutines to finish and return the final value of the counter.
func NoRequestsProcessed() uint64 {
return 0
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package atomic_counters

import "testing"

func TestAtomicCounter(t *testing.T) {

t.Run("Counter values is correct!", func(t *testing.T) {
got := NoRequestsProcessed()
want := 10_000
if int(got) != want {
t.Fatalf("Got %d, want %d", got, want)
}
})
}
Loading