Skip to content

Commit

Permalink
feture: showcasing select statement
Browse files Browse the repository at this point in the history
  • Loading branch information
aholbreich committed Nov 11, 2024
1 parent 2175867 commit ead81c5
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions concurrency/goroutines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package goroutines

import (
"testing"
"time"
)

func TestAdd(t *testing.T) {
Expand All @@ -24,3 +25,33 @@ func TestChannelSynchronization(t *testing.T) {
<-done // this is blocked until something is pushed into.

}

// Showecase of the very nice Select feature
func TestSelectWithTimeout(t *testing.T) {

ch1 := make(chan int)
ch2 := make(chan int)

// Start two goroutines with fixed delays
go func() {
time.Sleep(300 * time.Millisecond)
ch1 <- 10
}()
go func() {
time.Sleep(700 * time.Millisecond)
ch2 <- 20
}()

select { //accepts what comes firts.useful for tasks like multiplexing, timeouts

case result := <-ch1:
expected := 10
if result != expected {
t.Errorf("Expected %d from ch1, but got %d", expected, result)
}
case result := <-ch2:
t.Errorf("Did not expect to receive from ch2, but got %d", result)
case <-time.After(500 * time.Millisecond):
t.Error("Timeout occurred, but ch1 should have sent a value first")
}
}

0 comments on commit ead81c5

Please sign in to comment.