使用select时,通道缺少偶数

问题描述 投票:-1回答:1

我正在使用此函数来获取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时,通道缺少偶数,例如输出:

跌落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 85 87 89 91 93 95 97 99 0 0

哪里是2,4,6,8等..?

为什么在关闭频道之后它会向c频道发送零?我认为它会等待新数据进入并获得'默认'案例?

go
1个回答
5
投票

这是因为你正在从频道阅读两次。

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

这是一个例子:https://play.golang.org/p/ZdSOPe1Gj13

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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.