Go Closures and Goroutines: Difference between revisions
Jump to navigation
Jump to search
(One intermediate revision by the same user not shown) | |||
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. | 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. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
syncPoint := sync.WaitGroup{} | syncPoint := sync.WaitGroup{} | ||
Line 21: | Line 21: | ||
syncPoint.Done() | syncPoint.Done() | ||
syncPoint2.Wait() | syncPoint2.Wait() | ||
/syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 20:35, 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 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()