码迷,mamicode.com
首页 > 编程语言 > 详细

golang 实现线程池

时间:2017-02-06 12:22:44      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:任务   number   ror   make   down   add   ret   int   pac   

package main

import (
	"fmt"
	"time"
)

type Pool struct {
	Queue chan func() error;
	RuntineNumber int;
	Total int;

	Result chan error;
	FinishCallback func();
}

//初始化
func (self *Pool) Init(runtineNumber int,total int)  {
	self.RuntineNumber = runtineNumber;
	self.Total = total;
	self.Queue = make(chan func() error, total);
	self.Result = make(chan error, total);
}

func (self *Pool) Start()  {
	//开启 number 个goruntine
	for i:=0;i<self.RuntineNumber;i++ {
		go func() {
			for {
				task,ok := <-self.Queue
				if !ok {
					break;
				}
				err := task();
				self.Result <- err;
			}
		}();
	}

	//获取每个任务的处理结果
	for j:=0;j<self.RuntineNumber;j++ {
		res,ok := <-self.Result;
		if !ok {
			break;
		}
		if res != nil {
			fmt.Println(res);
		}
	}

	//结束回调函数
	if self.FinishCallback != nil {
		self.FinishCallback();
	}
}

//关闭
func (self *Pool) Stop()  {
	close(self.Queue);
	close(self.Result);
}

func (self *Pool) AddTask(task func() error)  {
	self.Queue <- task;
}

func (self *Pool) SetFinishCallback(fun func())  {
	self.FinishCallback = fun;
}


func main()  {
	var p Pool;
	url := []string{"11111","22222","33333","444444","55555","66666","77777","88888","999999"};
	p.Init(9, len(url));

	for i := range url {
		u := url[i];
		p.AddTask(func() error {
			return Download(u);
		});
	}

	p.SetFinishCallback(DownloadFinish);
	p.Start();
	p.Stop();
}

func Download(url string) error {
	time.Sleep(1*time.Second);
	fmt.Println("Download " + url);
	return nil;
}

func DownloadFinish()  {
	fmt.Println("Download finsh");
}

  

golang 实现线程池

标签:任务   number   ror   make   down   add   ret   int   pac   

原文地址:http://www.cnblogs.com/hanyouchun/p/6369736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!