go语言实现简单的goroutine崩溃重启

最近因为工作需要,转战go语言。有事没事就写点代码练练手,望有不足或错误之处,不吝赐教。

package main

import (
	"fmt"
	"time"
)

var testchan = make(chan int, 0)//全局通道

//goroutine运行代码
func test(c chan int, index int) {
	//recover主动抓取panic(err)
	defer func() {
		if err := recover(); err != nil {
			if err == "restart" {
				test2(index)
				fmt.Printf("[%v]recover: %v\n", index, err)
			}
		}
	}()

	fmt.Printf("test%v start\n", index)
	for {
		select {
		case value, ok := <-c:
			if !ok {//通道关闭主动退出
				panic("chan is close")
			}
			if value == 0 {//测试;主动崩溃
				panic("restart")
			} else {
				fmt.Printf("%v goroutine out print %v\n", index, value)
			}
		}
	}
}
//重启goroutine
func test2(index int) {
	go test(testchan, index)
}

func main() {
	t := 0
	//开10个goroutine
	for i := 0; i < 10; i++ {
		go test(testchan, i)
	}
	for {
		t = t % 10
		testchan <- t
		time.Sleep(time.Second)
		t++
	}
}

以上就是一个简单的读取消息,goroutine崩溃重启的小demo。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值