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

Can buffered channel of size 1 give one delayed send of guarantee?

如前所述here: 大小为 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

buffered channel of size 1,如果上面代码不显示数据,是否保证接收到数据?

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

唯一可以保证接收 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 来达到同样的目的。