Go Closures and Goroutines: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Goroutines =Overview=")
 
Line 2: Line 2:
* [[Go_Language_Goroutines#Start_a_Goroutine|Goroutines]]
* [[Go_Language_Goroutines#Start_a_Goroutine|Goroutines]]
=Overview=
=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 may fall out of scope. 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.
<syntaxhighlight lang='go'>
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()
/syntaxhighlight>

Revision as of 20:33, 16 January 2024

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 may fall out of scope. 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. <syntaxhighlight lang='go'> 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() /syntaxhighlight>