我所有的问题都是用代码编写的...
我不知道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/