如此处所述:大小为 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 关注
- 94 浏览
添加回答
举报
0/150
提交
取消