Created
December 3, 2019 21:21
-
-
Save camisetags/45506b16e898aebf10286c9bf1aa19ae to your computer and use it in GitHub Desktop.
Producer Consumer
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" | |
"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