From a4efadbe8a284b7dc481c60628d96ebc4a0fc288 Mon Sep 17 00:00:00 2001 From: oabrivard Date: Mon, 21 Aug 2023 13:19:23 +0200 Subject: [PATCH] Solved 1-producer-consumer --- 1-producer-consumer/main.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/1-producer-consumer/main.go b/1-producer-consumer/main.go index e508e93..83847f5 100644 --- a/1-producer-consumer/main.go +++ b/1-producer-consumer/main.go @@ -13,19 +13,19 @@ import ( "time" ) -func producer(stream Stream) (tweets []*Tweet) { +func producer(stream Stream, ch chan *Tweet) { for { tweet, err := stream.Next() if err == ErrEOF { - return tweets + close(ch) } - tweets = append(tweets, tweet) + ch <- tweet } } -func consumer(tweets []*Tweet) { - for _, t := range tweets { +func consumer(ch chan *Tweet) { + for t := range ch { if t.IsTalkingAboutGo() { fmt.Println(t.Username, "\ttweets about golang") } else { @@ -38,11 +38,13 @@ func main() { start := time.Now() stream := GetMockStream() + ch := make(chan *Tweet) + // Producer - tweets := producer(stream) + go producer(stream, ch) // Consumer - consumer(tweets) + go consumer(ch) fmt.Printf("Process took %s\n", time.Since(start)) }