Created
December 4, 2015 09:59
-
-
Save ZhandosKz/2ae31146c9d361cfa688 to your computer and use it in GitHub Desktop.
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" | |
"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