From 00b427a3abf5483363655d49f098e7d84bebb26e Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Sun, 28 Apr 2024 15:42:22 +0530 Subject: [PATCH] Add timeouts --- main.go | 6 ++++-- timeouts/timeouts.go | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 timeouts/timeouts.go diff --git a/main.go b/main.go index 75fdaf3..e7ea27b 100644 --- a/main.go +++ b/main.go @@ -6,7 +6,8 @@ package main // import "git.sangeeth.dev/gobyexample/errors" // import "git.sangeeth.dev/gobyexample/goroutines" // import "git.sangeeth.dev/gobyexample/channels" -import "git.sangeeth.dev/gobyexample/cselect" +// import "git.sangeeth.dev/gobyexample/cselect" +import "git.sangeeth.dev/gobyexample/timeouts" func main() { // runes.Runes() @@ -15,5 +16,6 @@ func main() { // errors.Errors() // goroutines.Goroutines() // channels.Channels() - cselect.Select() + // cselect.Select() + timeouts.Timeouts() } diff --git a/timeouts/timeouts.go b/timeouts/timeouts.go new file mode 100644 index 0000000..f47c478 --- /dev/null +++ b/timeouts/timeouts.go @@ -0,0 +1,24 @@ +package timeouts + +import ( + "fmt" + "math/rand" + "time" +) + +func slowMath(a, b int, result chan<- int) { + time.Sleep(time.Duration(rand.Intn(5)) * time.Second) + result <- a + b +} + +func Timeouts() { + result := make(chan int, 1) + go slowMath(3, 3, result) + + select { + case res := <-result: + fmt.Println("Got result:", res) + case <-time.After(3 * time.Second): + fmt.Println("Waited for 3 second, no result :(") + } +}