为了账号安全,请及时绑定邮箱和手机立即绑定

使用 select 时转到通道丢失偶数

使用 select 时转到通道丢失偶数

Go
鸿蒙传说 2023-03-29 17:12:53
我正在使用此函数获取从 0 到 100 的数字。func addone(c chan int) {    for i:= 0; i <= 100; i++{        c <- i    }    close(c)}然后我试图输出它:func printone(c chan int) {    for {        select {            case <-c:                fmt.Println(<-c)                time.Sleep(time.Millisecond * 50)            default:                fmt.Println("dropped")        }    }}主要功能:func main() {    ch := make(chan int)    go addone(ch)    printone(ch)    }使用 select 时 Go channel 缺少偶数,例如它是输出的:下降 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 89 89 89 8 99 0 02、4、6、8 等在哪里?为什么在关闭通道后它会向c通道发送零?我认为它会在新数据进入并获得“默认”案例之前等待?
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

这是因为您正在从频道中读取两次。

首先尝试将通道数据分配给变量。

package main


import "time"

import "fmt"


func main() {


    // For our example we'll select across two channels.

    c1 := make(chan string)

    c2 := make(chan string)


    // Each channel will receive a value after some amount

    // of time, to simulate e.g. blocking RPC operations

    // executing in concurrent goroutines.

    go func() {

        time.Sleep(1 * time.Second)

        c1 <- "one"

    }()

    go func() {

        time.Sleep(2 * time.Second)

        c2 <- "two"

    }()


    // We'll use `select` to await both of these values

    // simultaneously, printing each one as it arrives.

    for i := 0; i < 2; i++ {

        select {

        case msg1 := <-c1:

            fmt.Println("received", msg1)

        case msg2 := <-c2:

            fmt.Println("received", msg2)

        }

    }

}


查看完整回答
反对 回复 2023-03-29
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信