我正在测试,如果我把函数的开头,像这样:sync.WaitGroupdefer wg.Done()
package main
import (
"fmt"
"sync"
"time"
)
func worker(wg *sync.WaitGroup, id int) error {
defer wg.Done() // put here cause error
fmt.Printf("Worker %v: Finished\n", id)
if true {
return nil
}
return nil
}
var wg sync.WaitGroup // I should put `wg` outside of this function
func callWorker(i int){
fmt.Println("Main: Starting worker", i)
fmt.Printf("Worker %v: Finished\n", id)
wg.Add(1)
go worker(&wg, i)
wg.Wait()
}
func main() {
for i := 0; i < 1000; i++ {
go callWorker(i)
}
time.Sleep(time.Second * 60)
fmt.Println("Main: Waiting for workers to finish")
fmt.Println("Main: Completed")
}
在某些情况下,我会得到,像这样WaitGroup is reused before previous Wait has returned
但是如果我把函数的末尾放进去,它就能成功运行,为什么呢?defer wg.Done()
func worker(wg *sync.WaitGroup, id int) error {
fmt.Printf("Worker %v: Finished\n", id)
if true {
return nil
}
defer wg.Done() // put here, it is ok
return nil
}
智慧大石
12345678_0001
相关分类