Would this code cause a panic after GC in Go1.5?

Issue

package main

import "time"

var x = []string{}

func main() {
    go func() {
        for {
            y := x
            y = append(y, "aa")
        }
    }()
    go func() {
        for {
           x = []string{"123"}
        }
    }()
    for {
        time.Sleep(1)
    }
}

guess like when x (for example, the address of 123) is not really assigned to y, and x is assigned to a new address like 124.
and just this time gc happened, would the address of 123 be recycled and cause a panic?

Solution

No. First of all, x has a global scope. So GC won’t happen until a new value with new address is assign to it.

Now when a new value is assign, two things can happen:

  1. Goroutine assigning y to x happens. It get assign to y. Then no GC will happen.
  2. It will get new value with new address before first step happens.

I don’t know what you are trying to do. But there’s no panic even if goroutine runs simultaneously. X always has a value.

Since you asked that whether assignment is atomic: No normal assignment is atomic.

Answered By – khrm

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.