2 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
是的,您可以sync.WaitGroup按如下方式使用:
wg := sync.WaitGroup{}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
wg.Add(1) // add a waitgroup before calling the async function
player.Exec(command, func(response map[string]interface{}){
defer wg.Done() // release when this function returns
if response["statusCode"]==float64(0) { // ok
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage("<b>"+response["statusMessage"].(string)+"</b>")
fmt.Println("playerExec: "+time.Now().Format("20060102150405"))
} else { // failed to process
w.WriteHeader(http.StatusBadRequest) // 400
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage(response["statusMessage"].(string))
}
})
wg.Wait() // this will block until all the resources are released
fmt.Println("cmd: "+time.Now().Format("20060102150405"))
})

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
http:來(lái)自 main.main.func1.1 的多余 response.WriteHeader 調(diào)用
如果您WriteHeader在通過(guò)Write. 這就是為什么 WriteHeader 是額外的或superfluous.
在等待你的 exec 完成時(shí),你可以在你的閉包中使用 waitgroup 。
wg.Wait()將等到您的 exec 回調(diào)返回
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
wg.Add(1)
player.Exec(command, func(response map[string]interface{}){
defer wg.Done()
if response["statusCode"]==float64(0) { // ok
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage("<b>"+response["statusMessage"].(string)+"</b>")
fmt.Println("playerExec: "+time.Now().Format("20060102150405"))
} else { // failed to process
w.WriteHeader(http.StatusBadRequest) // 400
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage(response["statusMessage"].(string))
}
})
wg.Wait()
// Time.Sleep(Time.Seconds*2)
fmt.Println("cmd: "+time.Now().Format("20060102150405"))
})
- 2 回答
- 0 關(guān)注
- 171 瀏覽
添加回答
舉報(bào)