Skip to content

Commit 8febaad

Browse files
authored
Atomic counters (#168)
2 parents 8e1652c + 1ae9c5d commit 8febaad

4 files changed

Lines changed: 54 additions & 1 deletion

File tree

internal/exercises/catalog.yaml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,15 @@ concepts:
229229
- Close the jobs channel after sending all work to signal workers to finish.
230230
- Use strings.TrimSpace() to clean message strings by removing leading/trailing whitespace.
231231
- Collect exactly len(logs) results to ensure all work is processed.
232-
232+
- slug: 44_atomic_counters
233+
title: Atomic Counters
234+
test_regex: ".*"
235+
hints:
236+
- Use `sync/atomic` package to create and increment atomic counter.
237+
- Launch 10,000 anonymous go routines that simultaneously increment the counter.
238+
- Use WaitGroups to wait for all go routines to finish.
239+
240+
233241
projects:
234242
- slug: 101_text_analyzer
235243
title: Text Analyzer (Easy)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package atomic_counters
2+
3+
import (
4+
"sync"
5+
"sync/atomic"
6+
)
7+
8+
func NoRequestsProcessed() uint64 {
9+
10+
var ops atomic.Uint64
11+
var wg sync.WaitGroup
12+
13+
wg.Add(10_000)
14+
for range 10_000 {
15+
go func() {
16+
defer wg.Done()
17+
ops.Add(1)
18+
}()
19+
}
20+
wg.Wait()
21+
return ops.Load()
22+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package atomic_counters
2+
3+
// TODO: Assume you have to keep track of the number of requests processed
4+
// by an applications to display on a dashboard.
5+
// 1. Launch 10_000 goroutines that increment a counter.
6+
// 2. Wait for all goroutines to finish and return the final value of the counter.
7+
func NoRequestsProcessed() uint64 {
8+
return 0
9+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package atomic_counters
2+
3+
import "testing"
4+
5+
func TestAtomicCounter(t *testing.T) {
6+
7+
t.Run("Counter values is correct!", func(t *testing.T) {
8+
got := NoRequestsProcessed()
9+
want := 10_000
10+
if int(got) != want {
11+
t.Fatalf("Got %d, want %d", got, want)
12+
}
13+
})
14+
}

0 commit comments

Comments
 (0)