Created
December 10, 2021 06:31
-
-
Save priyankshah217/26f133a84f0f332d5e01f044a25054be to your computer and use it in GitHub Desktop.
ProducerConsumer In Go
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" | |
"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