0
0
Goprogramming~30 mins

Channel synchronization in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Channel synchronization
📖 Scenario: You are building a simple Go program where two goroutines need to coordinate their actions using channels. This is like two friends passing notes to each other to stay in sync.
🎯 Goal: Create a Go program that uses a channel to synchronize two goroutines. One goroutine will send a message, and the other will wait to receive it before printing it.
📋 What You'll Learn
Create a channel of type string called messageChan
Start a goroutine named sender that sends the string "Hello from sender" into messageChan
Start a goroutine named receiver that receives from messageChan and stores the value in a variable called msg
Print the received message msg in the receiver goroutine
Use sync.WaitGroup to wait for both goroutines to finish before the main function exits
💡 Why This Matters
🌍 Real World
Channels and goroutines are used in Go to build fast and efficient programs that do many things at once, like web servers or data processors.
💼 Career
Understanding channel synchronization is important for Go developers working on concurrent applications, ensuring safe communication between parts of a program.
Progress0 / 4 steps
1
Create the channel
Create a channel of type string called messageChan using make.
Go
Hint

Use make(chan string) to create the channel.

2
Add a WaitGroup and start sender goroutine
Import sync. Create a sync.WaitGroup called wg. Add 2 to wg. Start a goroutine named sender that sends the string "Hello from sender" into messageChan and calls wg.Done() when finished.
Go
Hint

Use wg.Add(2) before starting goroutines. Use defer wg.Done() inside the goroutine.

3
Start receiver goroutine to receive and print message
Start a goroutine named receiver that receives from messageChan into a variable called msg. Then print msg. Call wg.Done() when finished.
Go
Hint

Use msg := <-messageChan to receive from the channel.

4
Wait for goroutines to finish
Add wg.Wait() at the end of main to wait for both goroutines to finish before exiting.
Go
Hint

Use wg.Wait() to wait for all goroutines to finish.