Skip to content

Instantly share code, notes, and snippets.

@moinuddin14
Last active November 18, 2024 01:32
Show Gist options
  • Save moinuddin14/2ab93e3c8a4939d67054915f88c2a609 to your computer and use it in GitHub Desktop.
Save moinuddin14/2ab93e3c8a4939d67054915f88c2a609 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
func main() {
// Create a WaitGroup
var wg sync.WaitGroup
// Create an unbuffered channel
messageChannel := make(chan string)
// Add 2 to the WaitGroup counter (for two goroutines)
wg.Add(2)
// Immediately invoked function for the first goroutine
go func() {
defer wg.Done() // Mark this goroutine as done
messageChannel <- "Hello" // Send "Hello" to the channel
}()
// Immediately invoked function for the second goroutine
go func() {
defer wg.Done() // Mark this goroutine as done
messageChannel <- "World" // Send "World" to the channel
}()
// Start a goroutine to wait for all goroutines to finish and then close the channel
go func() {
wg.Wait() // Wait for the two goroutines to finish
close(messageChannel) // Close the channel to signal no more data
}()
// Infinite for loop to read messages from the channel
for msg := range messageChannel {
fmt.Println(msg)
}
fmt.Println("All done!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment