使用select

时间:2018-09-06 02:21:15

标签: go

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

已删除 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频道发送零?我以为会等到新数据进入并获得“默认”情况?

1 个答案:

答案 0 :(得分: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)
        }
    }
}