golang协程优雅退出

使用sync包中的Waitgroup结构,官方文档对它的描述:

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. 
Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

我们可以像下面这样使用waitgroup:

创建一个Waitgroup的实例,我们叫它wg
在每个goroutine启动前或者在里面调用wg.Add(1),也可以在创建n个goroutine前调用wg.Add(n)
当每个goroutine完成任务后,调用wg.Done()
在等待所有goroutine的地方调用wg.Wait(),wg.Done()前所有goroutine会阻塞,当所有goroutine都调用完wg.Done()之后它会返回。

代码目录结构如下:

src
|---main
	|---main.go
|---mqmgr
	|---mqmgr.go

代码如下:

mqmgr.go

package mqmgr

import (
	"fmt"
	"sync"
)

type MQMgr struct {
	addr      string
	port      int
	userName  string
	userPwd   string
	chanList  chan int
	waitGroup *sync.WaitGroup
}

func NewRabbitMQ() *MQMgr {
	return &MQMgr{
		chanList:  make(chan int, 1024),
		waitGroup: &sync.WaitGroup{},
	}
}

// 启动
func (m *MQMgr) Start() {
	m.waitGroup.Add(2)
	for i := 0; i < 2; i++ {
		go m.consumer()
	}
}

// 停止
func (m *MQMgr) Stop() {
	close(m.chanList)
	m.waitGroup.Wait()
}

// 向队列添加消息
func (m *MQMgr) PushMsg(val int) {
	m.chanList <- val
}

// 消费
func (m *MQMgr) consumer() {
	defer m.waitGroup.Done()
	for {
		select {
		case msg, ok := <-m.chanList:
			if ok {
				fmt.Println(msg)
			} else {
				fmt.Println("exit consumer")
				return
			}
		}
	}
}

main.go

package main

import (
	"fmt"
	"mqmgr"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	mqDemo := mqmgr.NewRabbitMQ()
	mqDemo.Start()

	// Handle SIGINT and SIGTERM.
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	fmt.Println(<-ch)

	// Stop the service gracefully.
	mqDemo.Stop()
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值