使用空 struct 做为 channel 中的通知载体

背景

使用 Golang 开发的时候,会经常使用 channel 来进行信号通知,即所传递的数据本身没有什么实际价值。

实现方式

之前一直使用如下方式

ch := make(chan int)

后来看到另外一种方式

ch := make(chan struct{})

两种方式的对比

使用空 struct 是对内存更友好的开发方式,在 go 源代码中针对 空struct 类数据内存申请部分,返回地址都是一个固定的地址。那么就避免了可能的内存滥用。

runtime/malloc.go :581

func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
    ...
    if size == 0 {
        return unsafe.Pointer(&zerobase)
    }
    ...
    // zerobase 是一个本 package 的局部变量
}

注意

这里需要注意的地方就是,不要将 size 为 0 和 zero-value 混淆。

zero-value 的解释如下

Variables declared without an explicit initial value are given their zero value.

默认值占用内存空间为 0 不是一个概念 ,示例如下

func main() {
    array := [0]int{}
    var a string

    fmt.Printf("%d\n", unsafe.Sizeof(array))
    fmt.Printf("%d\n", unsafe.Sizeof(a))
}

OutPut:
0
16

想法

以后代码这么写,应该会好一些。

type notify struct{}

func main() {
    ch := make(chan notify)
    ch <- notify{}
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值