GO语言技巧之友好关闭 chan

在go语言中,如果多次close 管道会产生 panic,可能需要 recover 才使程序恢复正常。

例:

package main

func main() {
	// 创建管道
	c := make(chan string, 1)
	close(c)
	close(c)	// 多次关闭
}

输出:
panic: close of closed channel

goroutine 1 [running]:
main.main()
        Z:/GO/test/useTools/test006/main.go:7 +0x5e
exit status 2

解决:
可以使用sync.Once ,它是 Golang package 中使方法只执行一次的对象实现。

package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once
	c := make(chan string, 1)

	once.Do(func() {
		fmt.Println("第一次关闭")
		close(c)
	})

	once.Do(func() {
		fmt.Println("第二次关闭")
		close(c)
	})
}

延伸阅读:

sync.Once 原理实现了一个类似锁的结构,使用变量 done 来记录函数的执行状态,使用 sync.Mutex 和 sync.atomic 来保证线程安全的读取 done 。

package sync

import (
	"sync/atomic"
)

// Once is an object that will perform exactly one action.
type Once struct {
	m    Mutex
	done uint32
}

// Do calls the function f if and only if Do is being called for the
// first time for this instance of Once. In other words, given
// 	var once Once
// if once.Do(f) is called multiple times, only the first call will invoke f,
// even if f has a different value in each invocation. A new instance of
// Once is required for each function to execute.
//
// Do is intended for initialization that must be run exactly once. Since f
// is niladic, it may be necessary to use a function literal to capture the
// arguments to a function to be invoked by Do:
// 	config.once.Do(func() { config.init(filename) })
//
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
//
// If f panics, Do considers it to have returned; future calls of Do return
// without calling f.
//
func (o *Once) Do(f func()) {
	if atomic.LoadUint32(&o.done) == 1 {
		return
	}
	// Slow-path.
	o.m.Lock()
	defer o.m.Unlock()
	if o.done == 0 {
		defer atomic.StoreUint32(&o.done, 1)
		f()
	}
}

参考连接:如何优雅地关闭通道

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值