1 Star 1 Fork 0

vincent/gcutil

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Worker.go 1.39 KB
一键复制 编辑 原始数据 按行查看 历史
vincent 提交于 2021-01-31 20:28 . feat(): goroutine pool
package routine
import (
"sync/atomic"
"time"
)
type functinType func(interface{}) error
// Worker is the actual executor who runs the tasks,
// it starts a goroutine that accepts tasks and
// performs function calls.
type Worker struct {
// pool who owns this routine.
pool *Pool
// task is a job should be done.
task chan functinType
// recycleTime will be update when putting a routine back into queue.
recycleTime time.Time
input chan interface{}
}
// run starts a goroutine to repeat the process
// that performs the function calls.
func (w *Worker) run() {
go func() {
//监听任务列表,一旦有任务立马取出运行
count := 1
var input interface{}
var f functinType
for count <=2{
select {
case str_temp, ok := <- w.input:
if !ok {
return
}
count ++
input = str_temp
case f_temp, ok := <-w.task:
if !ok {
//如果接收到关闭
atomic.AddInt32(&w.pool.running, -1)
close(w.task)
return
}
count ++
f = f_temp
}
}
err := f(input)
if err != nil{
//fmt.Println("执行任务失败")
}
//回收复用
w.pool.putWorker(w)
return
}()
}
// stop this routine.
func (w *Worker) stop() {
w.sendTask(nil)
close(w.input)
}
// sendTask sends a task to this routine.
func (w *Worker) sendTask(task functinType) {
w.task <- task
}
func (w *Worker) sendarg(input interface{}) {
w.input <- input
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/vincent78/gcutil.git
git@gitee.com:vincent78/gcutil.git
vincent78
gcutil
gcutil
v1.0.1

搜索帮助