Skip to content

Instantly share code, notes, and snippets.

@priyankshah217
Created December 10, 2021 06:31
Show Gist options
  • Save priyankshah217/26f133a84f0f332d5e01f044a25054be to your computer and use it in GitHub Desktop.
Save priyankshah217/26f133a84f0f332d5e01f044a25054be to your computer and use it in GitHub Desktop.
ProducerConsumer In Go
package main
import (
"fmt"
"strconv"
"sync"
"time"
)
const MaxItems = 100
type Message struct {
id int
desc string
}
var msgChan = make(chan Message)
func NewMessage(i int) Message {
fmt.Println("Producing message :: " + strconv.Itoa(i))
return Message{
id: i,
desc: fmt.Sprintf("this is message no %d", i),
}
}
func consumeMessage(m chan Message) {
for {
fmt.Println("Consuming :: " + (<-m).desc)
}
}
func produceMessage(w *sync.WaitGroup, m chan Message) {
defer w.Done()
for i := 0; i < MaxItems; i++ {
m <- NewMessage(i)
time.Sleep(time.Millisecond)
}
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go produceMessage(&wg, msgChan)
go consumeMessage(msgChan)
wg.Wait()
close(msgChan)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment