How can I completely terminate go func()?
```
package main
import (
"context"
"log"
"time"
)
func longRunningCalculation(timeCost int)chan string{
result:=make(chan string)
go func (){
time.Sleep(time.Second*(time.Duration(timeCost)))
log.Println("Still doing other things...")//Even if it times out, this goroutine is still doing other tasks.
result<-"Done"
log.Println(timeCost)
}()
return result
}
func jobWithTimeout(){
ctx,cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select{
case <-ctx.Done():
log.Println(ctx.Err())
return
case result:=<-longRunningCalculation(3):
log.Println(result)
}
}
func main() {
jobWithTimeout()
time.Sleep(time.Second*5)
}
```
2019/09/25 11:00:16 context deadline exceeded
2019/09/25 11:00:17 Still doing other things...
最近的评论