Will golang's GC free memory of object which only be referenced by a goroutine?

m := map[string]*Object {
    "a": obj
}
go func(obj *Object) {
    obj.Do()
}(m["a"])

delete(m, "a")

will GC free memory of obj when obj.Do() has not finished?

1 answer

  • answered 2018-05-16 06:26 Sean F

    The code will evaluate

    m["a"]
    

    which will give the pointer obj, then obj will be placed on a new stack for the goroutine, and then the goroutine will be started with that stack, and then obj will be removed from the map in the original goroutine. At that point the new goroutine stack will have a pointer to obj, and so obj will not be gc'ed for that reason until the 2nd goroutine completes execution.