Skip to content

Instantly share code, notes, and snippets.

@netmarkjp
Last active December 23, 2015 14:24
Show Gist options
  • Save netmarkjp/7bc8c2c24139638f5685 to your computer and use it in GitHub Desktop.
Save netmarkjp/7bc8c2c24139638f5685 to your computer and use it in GitHub Desktop.
golang async worker example
package main
import (
"fmt"
"time"
)
func main() {
task := make(chan string)
taskquit := make(chan bool)
workerquit := make(chan bool)
parallel := 3
for i := 0; i < parallel; i++ {
go func() {
loop:
for {
select {
case <-taskquit:
workerquit <- true
break loop
case job := <-task:
fmt.Println(job)
time.Sleep(1 * time.Second)
}
}
}()
}
go func() {
for n := 0; n < 7; n++ {
task <- fmt.Sprintf("お仕事%03d", n+1)
}
for {
if len(task) == 0 {
for i := 0; i < parallel; i++ {
taskquit <- true
}
}
time.Sleep(200 * time.Millisecond)
}
}()
for i := 0; i < parallel; i++ {
<-workerquit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment