首页 > 解决方案 > 使用选择时转到频道缺少偶数

问题描述

我正在使用这个函数来获取从 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 13 9 85 8 8 99 0 0

2、4、6、8等在哪里?

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

标签: go

解决方案


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

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

这是一个例子: 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)
        }
    }
}

推荐阅读