dream518518518 2017-03-30 18:39
浏览 195

Golang Goroutine无尽循环内存泄漏

I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:

go func(...) {
  for {
    buffer := make([]byte, 1024)
     ...
  } 
}

It slowly eats RAM. I understand that it is caused by calling make in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:

  var buffer []byte
  for {
    buffer = make([]byte, 1024)
     ...
    }
  } 

..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?

Also, if i will return this goroutine, will leaked memory be freed?

UPD: full memory leaking routine code:

go func(dataChannel chan []byte, errorChannel chan error) {
  for {
    buf := make([]byte, 1024)
    _, err := conn.Read(buf) 
    if err != nil {
      errorChannel<- err
      break
    }
    dataChannel<- buf
  } 
} (dataChannel, errorChannel)
  • 写回答

2条回答 默认 最新

  • dongshenghe1833 2017-03-30 20:51
    关注
      for {
            var mem runtime.MemStats
            runtime.ReadMemStats(&mem)
            fmt.Printf("alloc [%v] \t heapAlloc [%v] 
    ", mem.Alloc, mem.HeapAlloc)
            time.Sleep(2000 * time.Millisecond)
        }
    
    • added the above lines in your main function for loop (in the leaking code link given above)
    • new code : https://pastebin.com/UQbYuVN7
    • while running this shows that memory is being re-collected at regular intervals by gc
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!