How to make two functions calls f1(2)
and f1(1)
execute in parallel so that all the program would execute for 2 seconds not for 3.
package main
import (
"fmt"
"time"
)
// sleeps for `secs` seconds
func f1(secs time.Duration) (result string) {
fmt.Printf("waiting %V
", secs)
time.Sleep(secs * time.Second)
result = fmt.Sprintf("waited for %d seconds", secs)
return
}
// prints arg1, arg2
func f2(arg1, arg2 string) {
fmt.Println(arg1)
fmt.Println(arg2)
}
// this function executes for 3 seconds, because waits a lot
func runNotParallel() {
out1 := f1(2)
out2 := f1(1)
f2(out1, out2)
}
// golang parallel return functions
// todo: make it run so all the function will executes for 2 seconds not for 3
func runParallel() {
out1 := f1(2)
out2 := f1(1)
f2(out1, out2)
}
func main() {
runNotParallel()
runParallel()
}
I guess I can do it only with channels. Should I redefine function f1
or I can leave it as is and change only way I call it?