Go-select实现超时

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 )
 7 
 8 func main() {
 9     ch := make(chan int)
10     quit := make(chan bool)
11 
12     //新开协程
13     go func() {
14         for {
15             select {
16             case num := <-ch:
17                 fmt.Println("num:", num)
18             case <-time.After(3 * time.Second):
19                 fmt.Println("超时")
20                 quit <- true
21             }
22         }
23     }()
24     for i := 0; i < 3; i++ {
25         ch <- i
26     }
27     <-quit
28     fmt.Println("程序结束")
29 }
View Code

相关文章:

  • 2021-11-12
  • 2021-12-26
  • 2021-06-29
  • 2022-12-23
  • 2021-07-04
  • 2021-08-23
  • 2022-01-08
猜你喜欢
  • 2022-02-05
  • 2021-09-10
  • 2021-08-01
  • 2021-11-10
  • 2021-09-29
  • 2021-12-17
  • 2021-09-07
相关资源
相似解决方案