diff --git a/internal/exercises/catalog.yaml b/internal/exercises/catalog.yaml index 4a61cd5..b53ec7b 100644 --- a/internal/exercises/catalog.yaml +++ b/internal/exercises/catalog.yaml @@ -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) diff --git a/internal/exercises/solutions/44_atomic_counters/atomic_counters.go b/internal/exercises/solutions/44_atomic_counters/atomic_counters.go new file mode 100644 index 0000000..922e70a --- /dev/null +++ b/internal/exercises/solutions/44_atomic_counters/atomic_counters.go @@ -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() +} diff --git a/internal/exercises/templates/44_atomic_counters/atomic_counters.go b/internal/exercises/templates/44_atomic_counters/atomic_counters.go new file mode 100644 index 0000000..f448554 --- /dev/null +++ b/internal/exercises/templates/44_atomic_counters/atomic_counters.go @@ -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 +} diff --git a/internal/exercises/templates/44_atomic_counters/atomic_counters_test.go b/internal/exercises/templates/44_atomic_counters/atomic_counters_test.go new file mode 100644 index 0000000..5014bf9 --- /dev/null +++ b/internal/exercises/templates/44_atomic_counters/atomic_counters_test.go @@ -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) + } + }) +}