面试题答案
一键面试代码示例
package main
import (
"context"
"fmt"
"time"
)
func longRunningTask(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("任务被取消")
return
default:
fmt.Println("任务正在执行...")
time.Sleep(1 * time.Second)
}
}
}
在main
函数中调用:
func main() {
ctx, cancel := context.WithCancel(context.Background())
go longRunningTask(ctx)
time.Sleep(3 * time.Second)
cancel()
time.Sleep(2 * time.Second)
}
原理解释
- 创建context:通过
context.WithCancel(context.Background())
创建一个可取消的context
。context.Background()
是所有context
的根,WithCancel
函数返回一个context
和一个取消函数cancel
。 - 在goroutine中使用context:在
longRunningTask
函数中,通过select
语句监听ctx.Done()
通道。当ctx.Done()
通道接收到数据时,意味着context
被取消,此时可以进行清理操作并退出goroutine
。 - 取消操作:在
main
函数中,通过调用cancel()
函数来取消context
,这会向ctx.Done()
通道发送数据,从而通知正在执行的goroutine
停止任务。time.Sleep
语句用于模拟实际应用场景中的等待和操作。