首页 > 其他分享 >Go 100 mistakes - Expecting deterministic behavior using select and channels

Go 100 mistakes - Expecting deterministic behavior using select and channels

时间:2024-02-23 16:11:56浏览次数:24  
标签:ZZHPC Github return deterministic channels mistakes go run main

 

 

func main() {
    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{}, 1)

    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    go func() {
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("disconnection, return")
                return
            }
        }
    }()

    time.Sleep(10 * time.Microsecond)
    disconnectCh <- struct{}{}

    time.Sleep(time.Second)
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
0
1
2
3
4
5
6
7
8
9
disconnection, return
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
0
1
2
3
disconnection, return
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
0
disconnection, return

 

 

 

标签:ZZHPC,Github,return,deterministic,channels,mistakes,go,run,main
From: https://www.cnblogs.com/zhangzhihui/p/18029809

相关文章