diff --git a/internal/exercises/catalog.yaml b/internal/exercises/catalog.yaml index b8b9cad..d292275 100644 --- a/internal/exercises/catalog.yaml +++ b/internal/exercises/catalog.yaml @@ -251,3 +251,14 @@ projects: - "Use time.Parse() to parse time strings with known layouts" - "Use time.LoadLocation() to work with different timezones" - "Extract time components using .Date() and .Clock() methods" + +- slug: 39_waitgroup + title: "WaitGroups" + difficulty: beginner + topics: ["concurrency", "sync", "goroutines", "waitgroup"] + hints: + - "Use sync.WaitGroup to wait for goroutines." + - "Call wg.Add(n) before starting n goroutines; each must call wg.Done()." + - "Call wg.Wait() in the parent to block until completion." + + diff --git a/internal/exercises/solutions/39_waitgroup/waitGroup.go b/internal/exercises/solutions/39_waitgroup/waitGroup.go new file mode 100644 index 0000000..94b4dd8 --- /dev/null +++ b/internal/exercises/solutions/39_waitgroup/waitGroup.go @@ -0,0 +1,21 @@ +package waitgroup + +import ( + "sync" +) + +// The waitGroup in Go is used to wait for a collection of goroutines to finish executing + +func worker(wg *sync.WaitGroup, result *string) { + defer wg.Done() + *result = "Worker done" +} + +func waitGroup() string { + var wg sync.WaitGroup + result := "" + wg.Add(1) + go worker(&wg, &result) + wg.Wait() + return result +} diff --git a/internal/exercises/templates/39_waitgroup/waitgroup.go b/internal/exercises/templates/39_waitgroup/waitgroup.go new file mode 100644 index 0000000..9a18d45 --- /dev/null +++ b/internal/exercises/templates/39_waitgroup/waitgroup.go @@ -0,0 +1,18 @@ +package waitgroup + +import ( + "sync" +) + +// TODO: Implement these functions so tests pass + +func worker(wg *sync.WaitGroup, result *string) { + *result = "Worker done" +} + +func waitGroup() string { + var wg sync.WaitGroup + result := "" + go worker(&wg, &result) + return result +} diff --git a/internal/exercises/templates/39_waitgroup/waitgroup_test.go b/internal/exercises/templates/39_waitgroup/waitgroup_test.go new file mode 100644 index 0000000..386ddd3 --- /dev/null +++ b/internal/exercises/templates/39_waitgroup/waitgroup_test.go @@ -0,0 +1,11 @@ +package waitgroup + +import "testing" + +func TestWaitGroup(t *testing.T) { + got := waitGroup() + want := "Worker done" + if got != want { + t.Fatalf("waitGroup() = %q, want %q", got, want) + } +}