3 回答

TA貢獻1812條經驗 獲得超5個贊
您可以這樣做,select但由于要發送的值只評估一次,如果兩個通道都沒有準備好,要發送的值將在可以發送時過時。
因此,添加一個default案例,如果沒有任何通道準備好,您將在其中“睡眠”一點,然后再試一次(計算/獲取更新的新值以發送)。通過休眠,您不會消耗 CPU 資源:
s := make(chan<- int, 5)
r := make(<-chan int)
for {
v := valueToSend() // Evaluated each time we try to send
select {
case s <- v:
fmt.Println("Sent value:", v)
case vr := <-r:
fmt.Println("Received:", vr)
default: // If none are ready currently, we end up here
time.Sleep(time.Millisecond * 1)
}
}
請注意,檢查通道的長度或容量然后發送/接收不被認為是一個好的解決方案,因為在檢查其長度/上限和您嘗試發送/接收之間,通道可能未準備好,如下圖所示:
if len(r) > 0 {
// r is ready to receive
// Optional other code here,
// meanwhile another goroutine might receive the value from r!
r <- // If other goroutine received from r, this will block!
}

TA貢獻1966條經驗 獲得超4個贊
這是一個簡單的選擇:
select {
case s <- n:
// Successful send.
case n := <- r:
// Successful receive. Do something with n.
}
- 3 回答
- 0 關注
- 194 瀏覽
添加回答
舉報