Golang中的select使用
Contents
package main
import (
"fmt"
"time"
"sync"
)
type resultData struct {
Job int
Result bool
}
func main() {
n := 10
jobs := make(chan int, n)
result := make(chan resultData, n)
var wg sync.WaitGroup
wg.Add(n)
go publishJob(jobs, n)
go daemon(jobs, result, &wg)
wg.Wait()
fmt.Printf("finish %v jobs", n)
}
func publishJob(jobs chan int, n int) {
for i:=0;i<n ;i++{
jobs <- i
//time.Sleep(time.Duration(i) * time.Millisecond)
}
}
func daemon(jobs chan int, result chan resultData, wg *sync.WaitGroup) {
for {
select {
case j := <- jobs :
fmt.Printf("have jobs %v\n", j)
r := resultData{Job:j, Result:true}
result <- r
time.Sleep(time.Millisecond * 3)
case r := <- result :
fmt.Printf("job = %v, result = %v\n", r.Job, r.Result)
wg.Done()
default :
//fmt.Printf("in default \n")
}
}
}
输出结果如下:
[Running] go run "/home/sky/go-dsp/src/test2/main.go"
have jobs 0
job = 0, result = true
have jobs 1
have jobs 2
have jobs 3
job = 1, result = true
job = 2, result = true
have jobs 4
have jobs 5
have jobs 6
job = 3, result = true
job = 4, result = true
have jobs 7
job = 5, result = true
job = 6, result = true
job = 7, result = true
have jobs 8
have jobs 9
job = 8, result = true
job = 9, result = true
finish 10 jobs
[Done] exited with code=0 in 0.142 seconds