From 3eaddc8b3528c41a7f51dd8f7738344a56ae451e Mon Sep 17 00:00:00 2001 From: MaurĂ­cio Antunes Date: Wed, 14 Feb 2024 13:47:56 -0300 Subject: feat: New exercises (concurrency) --- exercises/concurrent/concurrent1/main_test.go | 45 +++++++++++++++++++++++++++ exercises/concurrent/concurrent2/main_test.go | 32 +++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 exercises/concurrent/concurrent1/main_test.go create mode 100644 exercises/concurrent/concurrent2/main_test.go (limited to 'exercises/concurrent') diff --git a/exercises/concurrent/concurrent1/main_test.go b/exercises/concurrent/concurrent1/main_test.go new file mode 100644 index 0000000..3965113 --- /dev/null +++ b/exercises/concurrent/concurrent1/main_test.go @@ -0,0 +1,45 @@ +// concurrent1 +// Make the tests pass! + +// I AM NOT DONE +package main_test + +import ( + "bytes" + "fmt" + "sync" + "testing" +) + +func TestPrinter(t *testing.T) { + var buf bytes.Buffer + print(&buf) + + out := buf.String() + + for i := 0; i < 3; i++ { + want := fmt.Sprintf("Hello from goroutine %d!", i) + if !bytes.Contains([]byte(out), []byte(want)) { + t.Errorf("Output did not contain expected string. Wanted: %q, Got: %q", want, out) + } + } +} + +func print(buf *bytes.Buffer) { + var wg sync.WaitGroup + var mu sync.Mutex + + goroutines := 3 + + for i := 0; i < goroutines; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + mu.Lock() + //fmt.Fprintf(buf, "Hello from goroutine %d!\n", i) + mu.Unlock() + }(i) + } + + wg.Wait() +} diff --git a/exercises/concurrent/concurrent2/main_test.go b/exercises/concurrent/concurrent2/main_test.go new file mode 100644 index 0000000..2233259 --- /dev/null +++ b/exercises/concurrent/concurrent2/main_test.go @@ -0,0 +1,32 @@ +// concurrent2 +// Make the tests pass! + +// I AM NOT DONE +package main_test + +import ( + "sync" + "testing" +) + +func TestCounter(t *testing.T) { + counter := updateCounter() + if counter != 100 { + t.Errorf("Counter should be 100, but got %d", counter) + } +} + +func updateCounter() int { + var counter int + var wg sync.WaitGroup + + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + counter++ // Many goroutines trying to update the counter? We need some protection here! + }() + } + wg.Wait() + return counter +} -- cgit v1.2.3-70-g09d2