商君

导航

Go Example--工作池

package main

import (
	"fmt"
	"time"
)

func main() {
	jobs :=make(chan int,100)
	results := make(chan int,100)
	//启动3个协程
	for w:=1;w<=3;w++{
		go worker(w,jobs,results)
	}
	for j:=1;j<=9;j++{
		jobs<-j
	}
	close(jobs)
	for a:=1;a<=9;a++{
		<-results
	}
}
//每个协程中根据调度读取通道jobs数据
func worker(id int, jobs <-chan int,results chan <-int)  {
	for j:= range jobs{
		fmt.Println("worker",id,"processing job",j)
		time.Sleep(time.Second)
		results<-j*2
	}
}

posted on 2018-10-19 17:15  漫步者01  阅读(85)  评论(0编辑  收藏  举报