Use empty struct as notification carrier in channel

background

When developing with Golang, it is often channelused for signal notification, that is, the data passed has no real value in itself.

Method to realize

I have been using the following method before

ch := make(chan int)

Then I saw another way

ch := make(chan struct{})

Comparison of the two ways

Using empty structis a more memory-friendly development method. In the gosource code, for the empty structclass data memory application part, the return address is a fixed address. Then possible memory abuse is avoided.

runtime/malloc.go :581

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

Notice

The point to note here is not sizeto zero-valueconfuse 0 with .

zero-valueThe explanation is as follows

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

默认值and 占用内存空间为 0is not a concept, examples are as follows

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

idea

It should be better to write the code like this in the future.

type notify struct{}

func main() {
    ch := make(chan notify)
    ch <- notify{}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326038627&siteId=291194637