Go 将选择与超时一起使用

示例

所以在这里,我已删除的for循环,并提出了超时通过添加第二个case到select的是收益后3秒。因为selectjust一直等到ANY情况成立,所以第二次case触发,然后脚本结束,chatter()甚至没有机会完成。

// 将select语句与通道一起使用,用于超时等。
package main

import (
    "fmt"
    "time"
)

// Function that is "chatty"
//将单个参数设为一个通道以向下发送消息
func chatter(chatChannel chan<- string) {
    // 循环十次而死
    time.Sleep(5 * time.Second) // 睡5秒钟
    chatChannel<- fmt.Sprintf("This is pass number %d of chatter", 1)
}

// 主要功能
func main() {
    // 创建通道,它将仅接收字符串,而无需在该项目上使用缓冲区
    chatChannel := make(chan string)
    // 完成后清理频道
    defer close(chatChannel)

    // 从chat不休地开始执行例程(独立,无阻塞)
    go chatter(chatChannel)

    // select语句将阻塞该线程,直到满足以下两个条件之一
    // 因为我们有默认设置,所以只要聊天者不聊天,我们都会达到默认设置
    select {
    // 每当聊天者聊天时,我们都会捕获并输出
    case spam := <-chatChannel:
        fmt.Println(spam)
    // 如果聊天者聊天时间超过3秒,请停止等待
    case <-time.After(3 * time.Second):
        fmt.Println("Ain't no time for that!")
    }
}