1、select实现的超时机制

示例:

 

package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan int)
	quit := make(chan bool)

	//新开一个协程
	go func() {
		for {
			select {
			case num := <-ch:
				fmt.Println("num = ", num)
			case <-time.After(3 * time.Second):
				fmt.Println("超时")
				quit <- true
			}
		}

	}() //别忘了()

	for i := 0; i < 5; i++ {
		ch <- i
		time.Sleep(time.Second)
	}

	<-quit
	fmt.Println("程序结束")

}

执行结果:

 

num =  0
num =  1
num =  2
num =  3
num =  4
超时
程序结束

  

相关文章:

  • 2021-10-24
  • 2021-10-29
  • 2021-09-16
  • 2021-08-24
  • 2021-12-31
  • 2021-11-07
  • 2022-01-11
  • 2021-12-17
猜你喜欢
  • 2021-12-17
  • 2021-08-15
  • 2021-09-12
  • 2022-03-02
  • 2021-05-30
  • 2021-06-08
  • 2021-07-01
相关资源
相似解决方案