dpjhq00684 2019-07-24 22:55
浏览 12

需要帮助以了解GoLang中的垃圾收集

I'm a little bit confused with GoLang's garbage collector.

Consider this following code, where I implement reader interface for my type T.

type T struct {
   header Header
   data   []*MyDataType
}

func (t *T) Read(p []byte) (int, error) {
    t.Header = *(*Header) (t.readFileHeader(p))
    t.Data = *(*[]*MyDataType) (t.readFileData(p))
}

wherein the reader functions I will cast the data to MyDataType using the unsafe.Pointer which will point to slice created with the reflect module (this is more complicated, but for the sake of the example this should be enough)

func (t *T) readFileData(data []byte, idx int, ...) unsafe.Pointer {
    ...
    return unsafe.Pointer(&reflect.SliceHeader{Data : uintptr(unsafe.Pointer(&data[idx])), ...}) 
}

and If I am gonna read the data in different function

func (d *Dummy) foo() {
    data, _ := ioutil.ReadFile(filename)
    d.t.Read(data) <---will GC free data?
}

Now I'm confused if it is possible, that the GC will free loaded data from file after exiting the foo function. Or the data will be freed after the d.t is freed.

  • 写回答

2条回答 默认 最新

  • dongxian0421 2019-07-25 07:43
    关注

    To understand what GC might do to your variables, first you need to know how and where Go allocates them. Here is a good reading about escape analysis, that is how Go compiler decides where allocate memory, between stack or heap.

    Long story short, GC will free memory only if it is not referenced by your Go program.

    In your example, the reference to loaded data by data, _ := ioutil.ReadFile(filename) is passed to t.Data = *(*[]*MyDataType) (t.readFileData(p)) ultimately. Therefore, they will be referenced as long as (t *T) struct is referenced as well. As far as I can see from your code, the loaded data will be garbage-collected along with (t *T).

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致