0

In this piece of code, a goroutine is created and tries to read from a buffered channel.

But the buffer is empty and should block the receiver, but it didn't. It will run but output nothin.

package main

import "fmt"

func fun(c chan int) {
    fmt.Println(<-c)
}

func main() {
    ch := make(chan int, 1)
    //ch <- 1
    go fun(ch)
}
icza
  • 389,944
  • 63
  • 907
  • 827
Gabriel
  • 77
  • 1
  • 7

1 Answers1

3

First, the buffer is not empty, because you send a value on it:

ch <- 1

This send operation will not block because the channel is buffered.

Then you launch a goroutine, and the main() function ends. And with that, your program ends as well, it does not wait for other non-main goroutines to complete. For details, see No output from goroutine in Go.

Note that the same thing happens even if you comment out the send operation in main(): you launch a goroutine and then main() ends along with your app: it does not wait for the other goroutine.

To wait for other goroutines, often a sync.WaitGroup is used like this:

var wg = &sync.WaitGroup{}

func fun(c chan int) {
    defer wg.Done()
    fmt.Println(<-c)
}

func main() {
    ch := make(chan int, 1)
    ch <- 1

    wg.Add(1)
    go fun(ch)
    wg.Wait()
}

Then output will be (try it on the Go Playground):

1

For details, see Prevent the main() function from terminating before goroutines finish in Golang

icza
  • 389,944
  • 63
  • 907
  • 827