You can create a timeout
with the select
statement. To use timeouts with concurrent goroutines, you must
import "time"
.
Then, create a channel with time.After()
which as
parameter takes time. The call time.After(time.Second)
would fill the channel after a second.
Example
Timeout
Combined with select
, a simple timeout program can be
created:
package main
import "fmt"
import "time"
func main() {
select {
case <- time.After(2 * time.Second):
.Println("Timeout!")
fmt}
}
This will print “Timeout!” after the time has passed.
Goroutine
Timeouts can be combined with goroutine calls. Call a goroutine
f1
with a channel c1
. Making
go f1(c1)
. The goroutine writes in to the channel
c <- "message"
after waiting 10 seconds.
Then a timeout is made with time.After()
. As this:
package main
import "fmt"
import "time"
func f1(c chan string) {
for {
.Sleep(10 * time.Second)
time<- "10 seconds passed"
c }
}
func main() {
:= make(chan string)
c1 go f1(c1)
select {
case msg1 := <- c1:
.Println(msg1)
fmtcase <- time.After(3 * time.Second):
.Println("Timeout!")
fmt}
}
See what happens.