Junior — Middle
What techniques for handling parallel tasks are implemented in Go?
sobes.tech AI
Answer from AI
In Go, techniques for handling parallel tasks include:
-
Goroutines — lightweight threads started with the
gokeyword. They allow functions to run in parallel. -
Channels — mechanisms for communication between goroutines, enabling data transfer and synchronization.
-
Select — a construct to wait on multiple channel operations, allowing to handle data from multiple sources.
-
sync package — contains synchronization primitives like
Mutex,WaitGroup,Once, which help manage access to shared resources and coordinate goroutine completion.
Example of launching a goroutine and passing data through a channel:
package main
import (
"fmt"
)
func worker(ch chan string) {
ch <- "done"
}
func main() {
ch := make(chan string)
go worker(ch)
msg := <-ch
fmt.Println(msg) // output: done
}