1 回答
TA贡献1773条经验 获得超3个赞
这是您可以使用的简单样板:
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。
编辑:添加带有回调的示例函数:
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
*/
})
}这是您可以使用的简单样板:
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。
编辑:添加带有回调的示例函数:
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 关注
- 68 浏览
添加回答
举报