-2

As mentioned here: Buffered channel of size 1 can give you one delayed send of guarantee

In the below code:

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())
}

Output:

Current Unix Time: 1610599724
Data sent at: 1610599724

Does buffered channel of size 1, guarantee the receiving of data, if not displaying the data in the above code?

How to verify, if display() received data?

overexchange
  • 13,706
  • 19
  • 106
  • 276

1 Answers1

2

The only way you can guarantee the receiving goroutine received data is tell the caller that it did:

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
}

You can also use a sync.WaitGroup for the same purpose.

Burak Serdar
  • 37,605
  • 3
  • 27
  • 46