Timing out a goroutine
There are times that goroutines take more time than expected to finish—in such situations, we want to time out the goroutines so that we can unblock the program. This section presents two such techniques.
Timing out a goroutine – inside main()
This subsection presents a simple technique for timing out a goroutine. The relevant code can be found in the main()
function of timeOut1.go
:
func main() {
c1 := make(chan string)
go func() {
time.Sleep(3 * time.Second)
c1 <- "c1 OK"
}()
The time.Sleep()
call is used for emulating the time it normally takes for a function to finish its operation. In this case, the anonymous function that is executed as a goroutine takes about three seconds before writing a message to the c1
channel.
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(time.Second):
fmt.Println("timeout c1")
}
The purpose...