Junior — Middle
How is multi-threading managed in the Go language?
sobes.tech AI
Answer from AI
In the Go language, concurrency is managed using goroutines. A goroutine is a lightweight thread that is started with the go keyword before a function call. The Go scheduler within the runtime manages the execution of goroutines, distributing them across system threads.
For synchronization and data exchange between goroutines, channels are often used, which provide safe data transfer and help avoid race conditions.
Example of launching two goroutines:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(100 * time.Millisecond)
}
}
func main() {
go say("world") // start a goroutine
say("hello") // runs in the main thread
}
In this example, the say function is called in a separate goroutine, allowing two tasks to run in parallel.