Synchronize Goroutines with Channels

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This challenge aims to test your knowledge of using channels to synchronize execution across goroutines.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/channels("`Channels`") subgraph Lab Skills go/channels -.-> lab-15378{{"`Synchronize Goroutines with Channels`"}} end

Channel Synchronization

The problem to be solved in this challenge is to create a goroutine that performs some work and notifies another goroutine when it's done using a channel.

Requirements

To complete this challenge, you will need to:

  • Create a function named worker that takes a channel of type bool as a parameter.
  • Inside the worker function, perform some work and then send a value to the channel to notify that the work is done.
  • In the main function, create a channel of type bool with a buffer size of 1.
  • Start a goroutine that calls the worker function and passes the channel as a parameter.
  • Block the main function until a value is received from the channel.

Example

$ go run channel-synchronization.go
working...done

## If you removed the `<- done` line from this program, the
## program would exit before the `worker` even
## started.

Summary

In this challenge, you learned how to use channels to synchronize execution across goroutines. By creating a channel and passing it to a goroutine, you can wait for the goroutine to finish its work and notify you when it's done.

Other Go Tutorials you may like