Go Language Goroutines: Difference between revisions
Line 8: | Line 8: | ||
=Creation and Invocation= | =Creation and Invocation= | ||
<span id='go_keyword'></span>To explicitly create a goroutine, use the <code>[[Go_Language#go_keyword|go]]</code> [[Go_Language#Keywords|keyword]], by providing a function invocation. | <span id='go_keyword'></span>To explicitly create a goroutine and schedule it, use the <code>[[Go_Language#go_keyword|go]]</code> [[Go_Language#Keywords|keyword]], by providing a function invocation. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
Line 19: | Line 19: | ||
go somefunc(10) | go somefunc(10) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Note that this '''schedules''' a goroutine. It is not determined when it will be actually executed. | |||
<font color=darkkhaki>what happens with the result of the function?</font> | <font color=darkkhaki>what happens with the result of the function?</font> | ||
A goroutine exits when the code is complete. When the <code>main</code> goroutine is complete, all other goroutines are forced to exit. | A goroutine exits when the code is complete. When the <code>main</code> goroutine is complete, all other goroutines are forced to exit. |
Revision as of 02:18, 1 September 2023
Internal
Overview
A goroutine is a Go thread. Many goroutines execute within a single O/S thread, the main thread?. From the O/S point of view, only one thread is scheduled. The goroutine schedule is done by the Go runtime scheduler. The Go runtime scheduler uses a logical processor. The goroutines scheduled on a logical processor are executing concurrently, not |in parallel. However, it is possible to have more than one logical processor, each logical processors can be mapped onto an O/S thread, which may be scheduled to work on different cores. In this case, things may become parallel.
A goroutine is always created automatically, to run the main()
function.
Creation and Invocation
To explicitly create a goroutine and schedule it, use the go
keyword, by providing a function invocation.
func somefunc(i int) {
...
}
...
go somefunc(10)
Note that this schedules a goroutine. It is not determined when it will be actually executed.
what happens with the result of the function?
A goroutine exits when the code is complete. When the main
goroutine is complete, all other goroutines are forced to exit.