Junior — Middle
How is parallel and sequential task processing implemented in Go?
sobes.tech AI
Answer from AI
In Go, parallel task processing is implemented using goroutines — lightweight threads that are started with the go keyword. A goroutine can be launched to execute a function asynchronously, and it will run in parallel with other goroutines.
Sequential processing is the usual calling of functions without using go, where tasks are executed one after another.
Example of parallel processing:
package main
import (
"fmt"
"time"
)
func task(id int) {
fmt.Printf("Task %d started\n", id)
time.Sleep(time.Second)
fmt.Printf("Task %d finished\n", id)
}
func main() {
for i := 1; i <= 3; i++ {
go task(i) // launch goroutine
}
time.Sleep(2 * time.Second) // wait for goroutines to finish
}
In this example, three tasks are launched in parallel. If go is removed, tasks will execute sequentially.
Channels and sync.WaitGroup are often used for synchronization and control of goroutines.