36 lines
682 B
Go
36 lines
682 B
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"time"
|
||
)
|
||
|
||
func worker(id int, jobs <-chan int, results chan<- int) {
|
||
for j := range jobs {
|
||
fmt.Println("worker", id, "started job", j)
|
||
time.Sleep(time.Second)
|
||
fmt.Println("worker", id, "finished job", j)
|
||
results <- j * 2
|
||
}
|
||
}
|
||
|
||
// work_pool练习
|
||
func main() {
|
||
jobs := make(chan int, 100)
|
||
results := make(chan int, 100)
|
||
//开启三个goroutine
|
||
for w := 1; w <= 3; w++ {
|
||
go worker(w, jobs, results)
|
||
}
|
||
//五个任务,0-5的数字放到jobs这个通道中
|
||
for j := 1; j <= 5; j++ {
|
||
jobs <- j
|
||
}
|
||
//关闭job
|
||
close(jobs)
|
||
//把results这个通道中的数字,即jobs中的结果*2取出
|
||
for a := 1; a <= 5; a++ {
|
||
<-results
|
||
}
|
||
}
|