Loading

go 关闭通道来作为退出信号

  • 关闭channel之后,读出的值是false,当一个被关闭的channel中已经发送的数据都被成功接收后,后续的接收操作将不再阻塞,它们会立即返回一个零值。

  • 没关闭之前,<-done会阻塞住。

package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan bool)
    go func() {
        for {
            select {
            case <-done:
                fmt.Println("done的值:", <-done)
                return
            default:
                fmt.Println("监控中...")
                time.Sleep(1 * time.Second)
            }
        }
    }()
    time.Sleep(3 * time.Second)
    close(done)
    fmt.Println("程序退出")
}

可以用close(done)来通知其他goroutines

posted @ 2023-03-06 16:19  Everyday_Struggle  阅读(39)  评论(0)    收藏  举报