Golang slice append and reallocation

Answer #1 100 %

The GC does not collect the backing array until there are no references to the backing array. There are no races in the program.

Consider the scenario with no goroutines:

  a := make([]*A, 0, 100)
  for i := 0; i < 100; i++ {
    a = append(a, &A{i})
  }
  b := a
  for i := 0; i < 100; i++ {
    b = append(b, &A{i+100})
  }

The slice a will continue to reference the backing array with the first 100 pointers when append to b allocates a new backing array. The slice a is not left with a dangling reference to a backing array.

Now add the goroutine to the scenario:

  a := make([]*A, 0, 100)
  for i := 0; i < 100; i++ {
    a = append(a, &A{i})
  }
  b := a
  go read_slice(a, ch)
  for i := 0; i < 100; i++ {
    b = append(b, &A{i+100})
  }

The goroutine can happily use slice a. There's no dangling reference.

Now consider the program in the question. It's functionaly identical to the last snippet here.

You’ll also like:


© 2023 CodeForDev.com -