1 Star 0 Fork 0

Andyfoo / go-xutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
xthread.go 2.31 KB
一键复制 编辑 原始数据 按行查看 历史
Andyfoo 提交于 2019-09-21 00:47 . update
// Copyright 2019 Andyfoo
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package xthread
import (
"sync"
)
type TaskFun func() interface{}
type TaskChanFun func(ch1 chan interface{})
type TaskFinishFun func(data interface{})
type AllFinishFun func()
type Thread struct {
taskFuns []TaskFun
taskChanFuns []TaskChanFun
waitGroup sync.WaitGroup
}
func NewThread() Thread {
return Thread{}
}
func (t *Thread) AddTaskFuns(fun TaskFun) {
t.taskFuns = append(t.taskFuns, fun)
}
func (t *Thread) AddTaskChanFuns(fun TaskChanFun) {
t.taskChanFuns = append(t.taskChanFuns, fun)
}
func (t *Thread) Start(taskCallback TaskFinishFun, allFinishCallback AllFinishFun) {
ch1 := make(chan interface{})
for _, fun1 := range t.taskFuns {
//xlog.Info("run task:", k)
t.waitGroup.Add(1)
go func() {
defer t.waitGroup.Done()
ch1 <- fun1()
}()
}
for _, fun1 := range t.taskChanFuns {
//xlog.Info("run chan task:", k)
t.waitGroup.Add(1)
go func() {
defer t.waitGroup.Done()
fun1(ch1)
}()
}
go func() {
t.waitGroup.Wait()
close(ch1)
}()
go func() {
if taskCallback == nil {
for _ = range ch1 {
}
} else {
for data := range ch1 {
taskCallback(data)
}
}
if allFinishCallback != nil {
allFinishCallback()
}
}()
}
func (t *Thread) StartSync(taskCallback TaskFinishFun) {
ch1 := make(chan interface{})
for _, fun1 := range t.taskFuns {
//xlog.Info("run task:", k)
t.waitGroup.Add(1)
go func() {
defer t.waitGroup.Done()
ch1 <- fun1()
}()
}
for _, fun1 := range t.taskChanFuns {
//xlog.Info("run chan task:", k)
t.waitGroup.Add(1)
go func() {
defer t.waitGroup.Done()
fun1(ch1)
}()
}
go func() {
t.waitGroup.Wait()
close(ch1)
}()
if taskCallback == nil {
for _ = range ch1 {
}
} else {
for data := range ch1 {
taskCallback(data)
}
}
}
Go
1
https://gitee.com/andyfoo/go-xutils.git
git@gitee.com:andyfoo/go-xutils.git
andyfoo
go-xutils
go-xutils
v1.0.7

搜索帮助