In the following example, the timer sends a message to the channel every 1 second. It will automatically terminate when the count reaches 10 times.
func main() {
fmt.Println("Commencing countdown.")
tick := time.Tick(1 * time.Second)
for countdown := 10; countdown > 0; countdown-- {
v := <-tick
fmt.Println(countdown, v)
}
}

However, if it is necessary to cancel midway, the select statement must be used. Its format is as follows:
select {
case <-ch1:
// ...
case x := <-ch2:
// ...use x...
case ch3 <- y:
// ...
default:
// ...
}
If default is used in the select, it means that at the time of entering the select, one of the cases must be ready; otherwise, it will execute the default code as soon as it enters the select.
The select statement will be executed only once.
If there is no default in the select, and none of the channels have content when entering the select, then the select will block.
After improvements, the code example for canceling execution is as follows:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
stop := make(chan int)
go tick(stop)
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
stop <- 0
fmt.Println("已结束")
}
func tick(stop chan int) {
fmt.Println("Commencing countdown.")
tick := time.Tick(1 * time.Second)
for countdown := 10; countdown > 0; countdown-- {
select {
case v := <-tick:
{
fmt.Println(countdown, v)
break
}
case <-stop:
return
}
}
}
文章评论