Add timeouts

This commit is contained in:
Sangeeth Sudheer 2024-04-28 15:42:22 +05:30
parent 9fad6d576e
commit 00b427a3ab
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 28 additions and 2 deletions

View File

@ -6,7 +6,8 @@ package main
// import "git.sangeeth.dev/gobyexample/errors" // import "git.sangeeth.dev/gobyexample/errors"
// import "git.sangeeth.dev/gobyexample/goroutines" // import "git.sangeeth.dev/gobyexample/goroutines"
// import "git.sangeeth.dev/gobyexample/channels" // 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() { func main() {
// runes.Runes() // runes.Runes()
@ -15,5 +16,6 @@ func main() {
// errors.Errors() // errors.Errors()
// goroutines.Goroutines() // goroutines.Goroutines()
// channels.Channels() // channels.Channels()
cselect.Select() // cselect.Select()
timeouts.Timeouts()
} }

24
timeouts/timeouts.go Normal file
View File

@ -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 :(")
}
}