Skip to content

Instantly share code, notes, and snippets.

@camisetags
Created December 3, 2019 21:21
Show Gist options
  • Save camisetags/45506b16e898aebf10286c9bf1aa19ae to your computer and use it in GitHub Desktop.
Save camisetags/45506b16e898aebf10286c9bf1aa19ae to your computer and use it in GitHub Desktop.
Producer Consumer
package main
import (
"fmt"
"time"
"math/rand"
"sync"
)
type Message struct {
Title string
Content int
}
func sleep() {
randomTime := rand.Intn(5)
time.Sleep(time.Duration(randomTime) * time.Second)
}
func produc(m chan Message, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
m <- Message{ Title: "message", Content: i }
fmt.Println("Produced message ", i)
sleep()
}
fmt.Println("Finished producing messages")
wg.Done()
}
func consum(m chan Message, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
receivedValue := <- m
sleep()
fmt.Println("Message received ", receivedValue.Content)
}
fmt.Println("Finished consuming messages")
wg.Done()
}
func main() {
messageChannel := make(chan Message, 3)
var wg sync.WaitGroup
wg.Add(2)
go consum(messageChannel, &wg)
go produc(messageChannel, &wg)
wg.Wait()
fmt.Println("Finished producer and consumer")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment