Created
March 8, 2019 17:23
-
-
Save 0xdeadbad/b000fde4c6797d84b332987f2206e847 to your computer and use it in GitHub Desktop.
Very simples example using Goroutines, Context and WaitGroup
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" | |
"sync" | |
"math/rand" | |
"time" | |
"context" | |
) | |
func consumer(ctx context.Context, wg *sync.WaitGroup, ch chan string) { | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("Context has been canceled. Exiting consumer.") | |
wg.Done() | |
return | |
case v := <-ch: | |
fmt.Printf("I've received a %s.\n", v) | |
time.Sleep(500*time.Millisecond) | |
} | |
} | |
} | |
func producer(ctx context.Context, wg *sync.WaitGroup, ch chan string) { | |
items := []string{"banana", "strawberry", "cranberry", "potato"} | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("Context has been canceled. Exiting producer.") | |
wg.Done() | |
return | |
default: | |
index := rand.Intn(len(items)) | |
ch <-items[index] | |
time.Sleep(500*time.Millisecond) | |
} | |
} | |
} | |
func main() { | |
// In this examples every producer should stop before consumer | |
// I'm yet a beginner programming go, any critic is welcome | |
var wg, pwg sync.WaitGroup | |
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second) | |
cctx, cancel := context.WithCancel(context.Background()) | |
ch := make(chan string) | |
pwg.Add(1) | |
go consumer(cctx, &pwg, ch) | |
for i := 0; i < 10; i ++ { | |
wg.Add(1) | |
go producer(ctx, &wg, ch) | |
} | |
wg.Wait() | |
fmt.Println("Canceling consumer.") | |
cancel() | |
pwg.Wait() | |
fmt.Println("Exiting program!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment