go channel for synchronization

tags: learning go programming

content

  • go channel could be used to block a go routine
func main() {
	ch := make(chan, bool)
	go func(ch chan bool) {
		fmt.Printf("doing someting")
		time.Sleep(time.Second)
		fmt.Printf("done")
		ch <- true
	}(ch)
	<-ch
}
  • in this example, main will wait for go routine to finish
  • more precisely, main is waiting for the channel to have something to read (main is being blocked!)
  • if there’s no channel in this context, main will finish before go routine can.
    • no output from go routine will be seen

up

go-channel-basics go-routine-basics

down

reference

Go by Example: Channel Synchronization