go by example part 3

This commit is contained in:
2022-01-05 22:56:08 +01:00
parent c1b7c64da2
commit c5983176c5
10 changed files with 337 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
// bound execution time
package main
import (
"fmt"
"time"
)
func main() {
// returns its result on a channel c1 after 2s
// channel is buffered, so the send in the goroutine is nonblocking
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
// select implementing a timeout
// res awaits the result and <-time
// After awaits a value to be sent after the timeout
// select proceeds with the first receive thats ready
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
// allow a longer timeout of 3s, then the receive from c2 will succeed and print the result
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}