在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()
			}
		})
}

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

查看所有标签

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

数据结构C++语言描述

数据结构C++语言描述

William Ford,William Topp / 刘卫东 沈官林 / 清华大学出版社 / 1999-09-01 / 58.00

一起来看看 《数据结构C++语言描述》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具