Skip to content

Instantly share code, notes, and snippets.

@iyashjayesh
Created March 28, 2023 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iyashjayesh/a6d96632de9cf1da0570eebf1013e3f7 to your computer and use it in GitHub Desktop.
Save iyashjayesh/a6d96632de9cf1da0570eebf1013e3f7 to your computer and use it in GitHub Desktop.
Example of asynchronous message processing in Go using channels and goroutines
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type Message struct {
Payload string
}
func main() {
wg := &sync.WaitGroup{}
ch := make(chan Message)
// starting a goroutine to receive messages from the channel asynchronously
go func() {
for msg := range ch {
sendMessage(msg)
fmt.Println("Message received:", msg.Payload)
wg.Done()
}
}()
for i := 1; i <= 10; i++ {
wg.Add(1)
ch <- Message{Payload: fmt.Sprintf("Message %d", i)}
}
wg.Wait()
close(ch)
}
func sendMessage(msg Message) {
duration := time.Duration((randInt(1, 5))) * time.Second
time.Sleep(duration)
fmt.Println("Message Send:", msg.Payload)
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
// try it - https://go.dev/play/p/Xye2RFiUy1b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment