sync.WaitGroup
是否正確嗎?它給出了預期的結果,但我不確定wg.Add(4)
和wg.Done()
的位置。與wg.Add()
一起添加四個套餐是否有意義?sync.WaitGroup示例正確嗎?
http://play.golang.org/p/ecvYHiie0P
package main
import (
"fmt"
"sync"
"time"
)
func dosomething(millisecs time.Duration, wg *sync.WaitGroup) {
duration := millisecs * time.Millisecond
time.Sleep(duration)
fmt.Println("Function in background, duration:", duration)
wg.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(4)
go dosomething(200, &wg)
go dosomething(400, &wg)
go dosomething(150, &wg)
go dosomething(600, &wg)
wg.Wait()
fmt.Println("Done")
}
結果(如預期):
Function in background, duration: 150ms
Function in background, duration: 200ms
Function in background, duration: 400ms
Function in background, duration: 600ms
Done
如果什麼DoSomething的()崩潰之前它可以做wg.Done()? –
我意識到這是舊的,但對於未來的人,我會建議在函數啓動時初始化「推遲wg.Done()」調用。 –