Senior
Kuidas teha kahe worker() täitmine paralleelselt asemel järjestikuna (6 sekundit → 3 sekundit)?
sobes.tech AI
Vastus AI-lt
In Go, functions can be executed in parallel using goroutines. If you have two worker() functions that are currently executed sequentially and take a total of 6 seconds, launching them in separate goroutines will run them in parallel, reducing the total time to approximately 3 seconds.
Example:
func() {
worker()
}()
func() {
worker()
}()
// To wait for both goroutines to finish, use sync.WaitGroup
var wg sync.WaitGroup
wg.Add(2)
func() {
defer wg.Done()
worker()
}()
func() {
defer wg.Done()
worker()
}()
wg.Wait()
This way, launching functions in goroutines and synchronizing them with WaitGroup allows their parallel execution.