2016-01-20 51 views
2

我正在使用goroutines /頻道。 這是我的代碼。 爲什麼超時情況沒有得到執行?Golang超時未與頻道執行

func main() { 
    c1 := make(chan int, 1) 

    go func() { 
     for { 
      time.Sleep(1500 * time.Millisecond) 
      c1 <- 10 
     } 
    }() 

    go func() { 
     for { 
      select { 
      case i := <-c1: 
       fmt.Println(i) 
      case <-time.After(2000 * time.Millisecond): 
       fmt.Println("TIMEOUT") // <-- Not Executed 
      } 
     } 
    }() 

    fmt.Scanln() 
} 

回答

2

您超時不會發生,因爲你夠程之一,每1.5秒對你c1通道發送的值(左右)反覆,如果沒有要接收值只會發生在您超時從c1持續2秒。

一旦值從c1接收時,在再次執行select一個time.After()呼叫將被製成,其返回在其上的值將只2秒鐘之後發送一個新通道下一次迭代。來自前一個select執行的超時通道將被丟棄,不再使用。

要2秒後接收超時,創建超時信道只有一次,例如:

timeout := time.After(2000 * time.Millisecond) 
for { 
    select { 
    case i := <-c1: 
     fmt.Println(i) 
    case <-timeout: 
     fmt.Println("TIMEOUT") // Will get executed after 2 sec 
    } 
} 

輸出:

10 
TIMEOUT 
10 
10 
10 
...