Senior
How to make the execution of two worker() functions parallel instead of sequential (6 seconds → 3 seconds)?
sobes.tech AI
Answer from AI
In Go, goroutines can be used for concurrent execution of functions. If you have two functions worker(), which currently run sequentially and take a total of 6 seconds, running them in separate goroutines will execute them in parallel, reducing the total time to approximately 3 seconds.
Example:
go func() {
worker()
}()
go func() {
worker()
}()
// To wait for both goroutines to finish, use sync.WaitGroup
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
worker()
}()
go func() {
defer wg.Done()
worker()
}()
wg.Wait()
Thus, launching functions in goroutines and synchronizing with WaitGroup allows them to run in parallel.