Skip to content

Instantly share code, notes, and snippets.

@arbrix
Forked from m0sth8/adv3.go
Last active December 9, 2015 04:59
Show Gist options
  • Save arbrix/eb29d75873d86ebef013 to your computer and use it in GitHub Desktop.
Save arbrix/eb29d75873d86ebef013 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
inner:
for len(items) > 0 {
sendWork = work
item = items[0]
select {
case sendWork <- item:
fmt.Println("send to worker", item)
items = items[1:]
default:
break inner
}
}
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