Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "sync"
- "time"
- )
- type msg struct {
- data []byte
- }
- var wg sync.WaitGroup
- func main() {
- // wait group used to control the flow in the demo
- // Not necessarily needed in real life :)
- wg = sync.WaitGroup{}
- c := readChan()
- for i := 0; i < 100; i++ {
- c <- msg{
- data: []byte("test"),
- }
- }
- close(c)
- // Using the wg so the program doens't end prematurely
- wg.Wait()
- }
- // readChan creates a chan, starts a worker listening on it,
- // and then returns the chan so we can add things to it!
- func readChan() (c chan msg) {
- c = make(chan msg)
- go Worker(c)
- return c
- }
- // Worker uses the chan to get messages
- func Worker(c chan msg) {
- wg.Add(1)
- fmt.Println("starting worker")
- count := 0
- stop := false
- for {
- select {
- case v, ok := <-c:
- if ok != true {
- stop = true
- }
- fmt.Println(string(v.data))
- count++
- }
- if stop {
- break
- }
- if count > 10 {
- go Worker(c)
- break
- }
- }
- fmt.Println("blocking..")
- time.Sleep(time.Second * 2)
- fmt.Println("done")
- wg.Done()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement