英文:
Why isn't this function cancelling?
问题
我有一段简单的代码,但由于某种原因,上下文没有取消函数。希望能得到一些帮助!
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
test(ctx)
}
func test(ctx context.Context) {
select {
case <-ctx.Done():
return
default:
time.Sleep(time.Second)
}
fmt.Println("Starting print")
time.Sleep(100 * time.Second)
fmt.Println("Ending print")
}
请帮我翻译这段代码。
英文:
I have a simple piece of code, but for some reason the context is not cancelling the function. Some help would be much appreciated!
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
test(ctx)
}
func test(ctx context.Context) {
select {
case <-ctx.Done():
return
default:
time.Sleep(time.Second)
}
fmt.Println("Starting print")
time.Sleep(100 * time.Second)
fmt.Println("Ending print")
}
</details>
# 答案1
**得分**: 2
选择语句执行默认子句,因为上下文没有被取消。当上下文被取消时,不会中断默认子句。
使用以下代码实现可取消的休眠:
```go
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
英文:
The select statement executes the default clause because the context is not canceled. The default clause is not interrupted when the context canceled.
Use this code to implement a cancelable sleep:
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论