Skip to content

Instantly share code, notes, and snippets.

@ZhandosKz
Created December 4, 2015 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ZhandosKz/2ae31146c9d361cfa688 to your computer and use it in GitHub Desktop.
Save ZhandosKz/2ae31146c9d361cfa688 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
wg.Add(1)
input := run(&wg)
for i:=0; i < 10; i++ {
input <- i+1
time.Sleep(time.Millisecond * 20)
}
close(input)
fmt.Println("close")
wg.Wait()
}
func run(wg *sync.WaitGroup) (input chan int) {
input = make(chan int)
work := make(chan int)
var items []int
go func() {
defer wg.Done()
for w := range work {
fmt.Println("work", w)
time.Sleep(time.Second * 2)
}
}()
go func() {
mainLoop: for {
var item int
var sendWork chan int
if len(items) > 0 {
sendWork = work
item = items[0]
}
select {
case i, ok :=<-input:
if ok {
fmt.Println("receive", i)
items = append(items, i)
} else if len(items) == 0 {
fmt.Println("Close queue")
close(work)
break mainLoop
}
case sendWork <- item:
fmt.Println("send to worker", item)
items = items[1:]
}
}
}()
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment