Skip to content

Commit

Permalink
feat: One more concurrency exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
mauricioabreu committed Feb 14, 2024
1 parent 749202c commit dac11a2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
43 changes: 43 additions & 0 deletions exercises/concurrent/concurrent3/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// concurrent3
// Make the tests pass!

// I AM NOT DONE
package main_test

import (
"bytes"
"fmt"
"testing"
)

func TestSendAndReceive(t *testing.T) {
var buf bytes.Buffer

messages := make(chan string)
sendAndReceive(&buf, messages)

got := buf.String()
want := "Hello World"

if got != want {
t.Errorf("got %q want %q", got, want)
}
}

func sendAndReceive(buf *bytes.Buffer, messages chan string) {
go func() {
messages <- "Hello"
messages <- "World"
close(messages)
}()

greeting := <-messages
fmt.Fprint(buf, greeting)

// Here we just receive the first message
// Consider using a for-range loop to iterate over the messages
_, ok := <-messages
if !ok {
fmt.Fprint(buf, "Channel is closed")
}
}
12 changes: 12 additions & 0 deletions info.toml
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,15 @@ A counter is a good example. Your counter could be updated with a different valu
Read a little about mutexes: https://pkg.go.dev/sync#Mutex.
"""

[[exercises]]
name = "concurrent3"
path = "exercises/concurrent/concurrent3/main_test.go"
mode = "test"
hint = """
Writing messages to closed channels will panic.
To avoid panics, we don't want to send messages to closed channels.
Remember: channels can be iterated using for-range loops.
"""

0 comments on commit dac11a2

Please sign in to comment.