Go Closures and Goroutines

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

A closure closes over the variables in the scope in which it was declared. When that closure is executed as a goroutine, some of the variables it closed over may fall out of scope. As the goroutines will continue to reference those variables, the runtime will know that the variable is still being held and therefore will transfer the associated value on the heap so the goroutine can still access it.

syncPoint := sync.WaitGroup{}
syncPoint2 := sync.WaitGroup{}
syncPoint.Add(1)
syncPoint2.Add(1)
	
{
  var s = "something"
  go func() {
    defer syncPoint2.Done()
    syncPoint.Wait()
	fmt.Printf("s: %s\n", s)
  }()
}

// at this point, the variable s fell out of scope, but the goroutine can still access it, and it will print "something"
syncPoint.Done()
syncPoint2.Wait()