Created
March 28, 2023 06:07
-
-
Save iyashjayesh/a6d96632de9cf1da0570eebf1013e3f7 to your computer and use it in GitHub Desktop.
Example of asynchronous message processing in Go using channels and goroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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