Skip to content

Instantly share code, notes, and snippets.

@m0sth8
Forked from ZhandosKz/adv3.go
Last active December 18, 2015 06:48
Show Gist options
  • Save m0sth8/1c80a1741d15ab6550f9 to your computer and use it in GitHub Desktop.
Save m0sth8/1c80a1741d15ab6550f9 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:]
case 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