go - 其他goroutine创建的指针的指针 channel

标签 go

我所有的问题都是用代码编写的...
我不知道golang是否具有堆内存和堆栈内存。
如果一个函式有自己的堆栈存储器,那么另一个函式可以读取它吗?
代码:

package main

import (
    "fmt"
    "math/rand"
    "strconv"
    "time"
)

type People struct {
    name string
    age int
}

func receiver(ch chan *People){
    for{
        // 2. Why the pointer a variable in receiver stack returned by <-ch can reach
        // the stack belongs to sender?
        fmt.Println((<-ch).name)
    }
}
func sender(ch chan *People){
    for{
        time.Sleep(3*time.Second)
        // 1. the People instance is created by sender and 
        // the pointer may points to the local stack in sender's call stack.
        ch <- &People{name: strconv.Itoa(rand.Int())}
    }
}
func main(){
    ch := make(chan *People, 10)
    go receiver(ch)
    go sender(ch)

    // join...
    time.Sleep(time.Hour)
}

最佳答案

Go编译器会进行转义分析,以检查对象是否应在堆栈或堆上。但是语言规范没有区别,这意味着编译器将来可能会采用与今天不同的方法。当然,我的意思是最优化和决策技术不是当今存在的一种创举。
检查此stack or heap
如果您使用转义分析标志构建程序:go build -gcflags="-m"您会注意到它显示:

(<-ch).name escapes to heap
...
 "&People literal escapes to heap"
因此,借助转义分析的编译器会事先知道可能是哪些东西,可能在堆栈中,什么应该在堆中。
=>这样,您就可以将怀疑的东西放到堆上。

关于go - 其他goroutine创建的指针的指针 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65456403/

相关文章:

Go:运行外部 Python 脚本

json - 使用 golang 从 http 网络服务器中提取特定的和最新的数据

go - travis-ci在使用go test时需要root权限,如何设置?

amazon-web-services - AWS Cognito API 身份验证流程 SDK

initialization - 用 Go 中的类型声明替换包装结构

validation - beego 验证接受无效数据

qt - 如果函数 raise()、activeWindow() 和其他函数不起作用,我如何将 QFileDialog 提升到前台?

go - Go中的每次测试覆盖率

json - 从嵌套的 JSON 字符串中检索元素

algorithm - 二数和算法