So I have a simple script that runs 11 times of calSauare function. However, I set wg.Add(10), so When I run script 1, it returns an error:
But, when I set time.Sleep(time.Second * 3)
to time.Sleep(time.Second *
)`. The program returns no error:
Why?
script 1:
package main
import (
"fmt"
"time"
"runtime"
"sync"
)
func calSauare(i int, wg *sync.WaitGroup) {
time.Sleep(time.Second * 3)
fmt.Println(i*i)
wg.Done()
}
func main() {
fmt.Println(runtime.NumCPU())
var wg sync.WaitGroup
wg.Add(10)
start := time.Now()
for i:=0; i<=10; i++ {
go calSauare(i,&wg)
}
wg.Wait()
duration := time.Since(start)
fmt.Println("This program took " ,duration)
}
script 2:
package main
import (
"fmt"
"time"
"runtime"
"sync"
)
func calSauare(i int, wg *sync.WaitGroup) {
time.Sleep(time.Second * 1)
fmt.Println(i*i)
wg.Done()
}
func main() {
fmt.Println(runtime.NumCPU())
var wg sync.WaitGroup
wg.Add(10)
start := time.Now()
for i:=0; i<=10; i++ {
go calSauare(i,&wg)
}
wg.Wait()
duration := time.Since(start)
fmt.Println("This program took " ,duration)
}