在GO里面使用try...catch...finally

栏目: Go · 发布时间: 7年前

内容简介:如果想开一个新的协程来跑你的方法时如果想做一个管理器,对管理你自己开的所有协程,在你关闭时,可以等他们都退出的时候,再退出
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()
			}
		})
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript语言精粹

JavaScript语言精粹

Douglas Crockford / 赵泽欣、鄢学鹍 / 电子工业出版社 / 2009-4 / 35.00元

本书通过对JavaScript语言的分析,甄别出好的和坏的特性,从而提取出相对这门语言的整体而言具有更好的可靠性、可读性和可维护性的JavaScript的子集,以便你能用它创建真正可扩展的和高效的代码。 雅虎资深JavaScript架构师Douglas Crockford倾力之作。 向读者介绍如何运用JavaScript创建真正可扩展的和高效的代码。一起来看看 《JavaScript语言精粹》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具