如此處所述:大小為 1 的緩沖通道可以為您提供一次延遲發送保證在下面的代碼中:package mainimport ( "fmt" "time")func display(ch chan int) { time.Sleep(5 * time.Second) fmt.Println(<-ch) // Receiving data}func main() { ch := make(chan int, 1) // Buffered channel - Send happens before receive go display(ch) fmt.Printf("Current Unix Time: %v\n", time.Now().Unix()) ch <- 1 // Sending data fmt.Printf("Data sent at: %v\n", time.Now().Unix())}輸出:Current Unix Time: 1610599724Data sent at: 1610599724如果上述代碼中沒有顯示數據,大小為1的緩沖通道是否保證數據的接收?如果收到數據,如何驗證?display()
1 回答

慕森王
TA貢獻1777條經驗 獲得超3個贊
您可以保證接收goroutine接收數據的唯一方法是告訴調用方它做了:
func display(ch chan int,done chan struct{}) {
time.Sleep(5 * time.Second)
fmt.Println(<-ch) // Receiving data
close(done)
}
func main() {
ch := make(chan int, 1) // Buffered channel - Send happens before receive
done:=make(chan struct{})
go display(ch,done)
fmt.Printf("Current Unix Time: %v\n", time.Now().Unix())
ch <- 1 // Sending data
fmt.Printf("Data sent at: %v\n", time.Now().Unix())
<-done
// received data
}
您也可以將 用于相同的目的。sync.WaitGroup
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消