Junior — Middle
Could you explain the concept of lightweight threads and how they differ from regular threads?
sobes.tech AI
Answer from AI
Lightweight threads (goroutines in Go) are an abstraction for parallel code execution that is lighter and more resource-efficient than traditional system threads.
Differences:
- Resources: goroutines occupy much less memory (usually a few kilobytes), whereas a system thread requires much more (usually megabytes).
- Scheduling: goroutines are scheduled by the Go scheduler within the process, not by the operating system, allowing for quick switching between them.
- Creation: starting a goroutine is very fast and cheap; thousands or even millions can be created simultaneously.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // runs the function in a separate goroutine
time.Sleep(time.Second) // wait to allow the goroutine to complete
}
Thus, lightweight threads enable efficient parallelism without significant overhead.