Home >Backend Development >Golang >Are Go Goroutines True Coroutines?
The Google I/O 2012 presentation "Go Concurrency Patterns" poses the question of whether goroutines, lightweight threads in the Go language, are implemented as coroutines.
Coroutine Definition and Comparison
A coroutine typically implies explicit control transfer mechanisms between different coroutines. Programmers can programmatically determine when a coroutine should suspend execution and pass control to another.
Goroutine Implementation
Go goroutines, in contrast, implicitly surrender control at specific but ultimately indeterminate points. For example, goroutines are suspended before executing I/O operations or sending data through channels. This approach allows programmers to write sequential, lightweight processes that effectively share state.
Implementation Details
The implementation of goroutines is akin to the "State Threads" library, operating at a lower level. Go directly interacts with the OS kernel without relying on external libraries.
Update: Proposed Coroutine Package
In 2023, Russ Cox proposed a standard coroutine package for Go, offering a framework for explicit control transfer and cooperative scheduling.
Additional Notes
Prior to Go 1.14, goroutines were scheduled non-preemptively, where the kernel could suspend threads at any time. Since Go 1.14, goroutines have been scheduled (almost) preemptively, allowing for more granular control over their execution.
The above is the detailed content of Are Go Goroutines True Coroutines?. For more information, please follow other related articles on the PHP Chinese website!