1 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是您可以使用的簡(jiǎn)單樣板:
finished := make(chan bool)
go func() {
/*
* Place your code here
*/
finished <- true
}()
select {
case <-time.After(timeout):
fmt.Println("Timed out")
case <-finished:
fmt.Println("Successfully executed")
}
分配time.Second*3或任何Duration變量timeout。
編輯:添加帶有回調(diào)的示例函數(shù):
func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {
finished := make(chan bool)
go func() {
myFunc()
finished <- true
}()
select {
case <-time.After(timeout):
return false
case <-finished:
return true
}
}
func main() {
success := timeoutMyFunc(3*time.Second, func() {
/*
* Place your code here
*/
})
}這是您可以使用的簡(jiǎn)單樣板:
finished := make(chan bool)
go func() {
/*
* Place your code here
*/
finished <- true
}()
select {
case <-time.After(timeout):
fmt.Println("Timed out")
case <-finished:
fmt.Println("Successfully executed")
}
分配time.Second*3或任何Duration變量timeout。
編輯:添加帶有回調(diào)的示例函數(shù):
func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {
finished := make(chan bool)
go func() {
myFunc()
finished <- true
}()
select {
case <-time.After(timeout):
return false
case <-finished:
return true
}
}
func main() {
success := timeoutMyFunc(3*time.Second, func() {
/*
* Place your code here
*/
})
}
- 1 回答
- 0 關(guān)注
- 93 瀏覽
添加回答
舉報(bào)