鍍金池/ 問答/Java  GO/ golang channel超時疑問

golang channel超時疑問

最近在學(xué)golang,學(xué)到協(xié)程channel超時這里,想試試多個協(xié)程如何判斷超時,自己寫了下,代碼如下:
開了10個協(xié)程,很奇怪為什么一半正常輸出,一半超時,只是簡單輸出1秒內(nèi)應(yīng)該都能正常輸出啊,很疑問,希望有人能解釋下。

package main

import (
    "fmt"
    "time"
)

func send(k int, ch chan int) {
    ch <- k
}

func main() {
    fmt.Println(time.Now().Unix())
    ch := make(chan int)
    timeout := make(chan bool)
    for k := 0; k < 10; k++ {
        go send(k, ch)
        go func() {
            time.Sleep(1 * time.Second)
            timeout <- true
        }()
    }

    for i := 0; i < 10; i++ {
        select {
        case <-ch:
            fmt.Println("receive:", <-ch)
        case <-timeout:
            fmt.Println("timeout")
        }
    }

    fmt.Println(time.Now().Unix())
}

/*
1535507000
receive: 1
receive: 3
receive: 5
receive: 7
receive: 9
timeout
timeout
timeout
timeout
timeout
1535507001

*/

回答
編輯回答
陌南塵
case <-ch:
            fmt.Println("receive:", <-ch)

你這里連續(xù)取了兩次值. 所以只需要五次循環(huán) ch 就已經(jīng)空了, 后面五次自然都是 timeout 了.

改成:

select {
        case c := <-ch: // 只取一次
            fmt.Println("receive:", c)
        case <-timeout:
            fmt.Println("timeout")
        }
2017年12月3日 20:53