大小为 1 的缓冲通道能否保证一次延迟发送?

如此处所述:大小为 1 的缓冲通道可以为您提供一次延迟发送保证


在下面的代码中:


package main


import (

    "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: 1610599724

Data sent at: 1610599724

如果上述代码中没有显示数据,大小为1的缓冲通道是否保证数据的接收?


如果收到数据,如何验证?display()


三国纷争
浏览 95回答 1
1回答

慕森王

您可以保证接收goroutine接收数据的唯一方法是告诉调用方它做了:func display(ch chan int,done chan struct{}) {&nbsp; &nbsp; time.Sleep(5 * time.Second)&nbsp; &nbsp; fmt.Println(<-ch) // Receiving data&nbsp; &nbsp; close(done)}func main() {&nbsp; &nbsp; ch := make(chan int, 1) // Buffered channel - Send happens before receive&nbsp; &nbsp; done:=make(chan struct{})&nbsp; &nbsp; go display(ch,done)&nbsp; &nbsp; fmt.Printf("Current Unix Time: %v\n", time.Now().Unix())&nbsp; &nbsp; ch <- 1 // Sending data&nbsp; &nbsp; fmt.Printf("Data sent at: %v\n", time.Now().Unix())&nbsp; &nbsp; <-done&nbsp; &nbsp;// received data}您也可以将 用于相同的目的。sync.WaitGroup
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go