Last active
December 23, 2015 14:24
-
-
Save netmarkjp/7bc8c2c24139638f5685 to your computer and use it in GitHub Desktop.
golang async worker example
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" | |
"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