内容简介:如果想开一个新的协程来跑你的方法时如果想做一个管理器,对管理你自己开的所有协程,在你关闭时,可以等他们都退出的时候,再退出
func Try(f func(), catch func(interface{}), finally func()) {
defer func() {
if finally != nil {
finally()
}
}()
defer func() {
if err := recover(); err != nil {
if catch != nil {
catch(err)
} else {
//loglogic.PFatal(err)//改成你自己的输出代码
}
}
}()
f()
}
如果想开一个新的协程来跑你的方法时
func GoTry(f func(), catch func(interface{}), finally func()) {
go Try(f, catch, finally)
}
如果想做一个管理器,对管理你自己开的所有协程,在你关闭时,可以等他们都退出的时候,再退出
//ThreadGo 子协程管理计数,可以等子协程都完成
//用它来管理所有开的协程,需要等这些线程都跑完
type ThreadGo struct {
Wg sync.WaitGroup //等待
Ctx context.Context
Cal context.CancelFunc
}
func NewThreadGo() *ThreadGo {
reuslt := new(ThreadGo)
reuslt.Ctx, reuslt.Cal = context.WithCancel(context.Background())
return reuslt
}
func (this *ThreadGo) CloseWait() {
this.Cal()
this.Wg.Wait()
}
//Go 在当前线程上跑
func (this *ThreadGo) Go(f func(ctx context.Context)) {
this.Wg.Add(1)
GoTry(func() {
f(this.Ctx)
}, nil, func() {
this.Wg.Done()
})
}
//GoTry 在新协程上跑
func (this *ThreadGo) GoTry(f func(ctx context.Context), catch func(interface{}), finally func()) {
this.Wg.Add(1)
GoTry(
func() {
f(this.Ctx)
},
catch,
func() {
defer this.Wg.Done()
if finally != nil {
finally()
}
})
}
//Try 在当前协程上跑
func (this *ThreadGo) Try(f func(ctx context.Context), catch func(interface{}), finally func()) {
this.Wg.Add(1)
Try(
func() {
f(this.Ctx)
},
catch,
func() {
defer this.Wg.Done()
if finally != nil {
finally()
}
})
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- RecyclerView使用指南(一)—— 基本使用
- 如何使用Meteorjs使用URL参数
- 使用 defer 还是不使用 defer?
- 使用 Typescript 加强 Vuex 使用体验
- [译] 何时使用 Rust?何时使用 Go?
- UDP协议的正确使用场合(谨慎使用)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Hard Thing About Hard Things
Ben Horowitz / HarperBusiness / 2014-3-4 / USD 29.99
Ben Horowitz, cofounder of Andreessen Horowitz and one of Silicon Valley's most respected and experienced entrepreneurs, offers essential advice on building and running a startup—practical wisdom for ......一起来看看 《The Hard Thing About Hard Things》 这本书的介绍吧!
Base64 编码/解码
Base64 编码/解码
RGB HSV 转换
RGB HSV 互转工具