MST

星途 面试题库

面试题:Go语言Context在并发任务取消中的应用

假设有一个主函数开启了多个goroutine进行并发任务,这些任务之间可能存在数据依赖。当其中一个任务出现异常时,需要通过Context来取消所有相关的goroutine。请描述实现思路并给出关键代码示例。
31.9万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建一个 context.Contextcontext.CancelFunc,通过 context.WithCancel 函数,CancelFunc 用于取消 Context
  2. context.Context 传递给每个 goroutine,每个 goroutine 应定期检查 ContextDone 通道,当通道关闭时,表示需要取消任务。
  3. 在任何一个 goroutine 检测到异常时,调用 CancelFunc,这会关闭 ContextDone 通道,其他 goroutine 检测到通道关闭后,停止执行。

关键代码示例

package main

import (
    "context"
    "fmt"
    "time"
)

func task(ctx context.Context, id int) {
    for {
        select {
        case <-ctx.Done():
            fmt.Printf("goroutine %d received cancel signal, exiting\n", id)
            return
        default:
            fmt.Printf("goroutine %d is working\n", id)
            time.Sleep(100 * time.Millisecond)
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    // 启动多个goroutine
    for i := 1; i <= 3; i++ {
        go task(ctx, i)
    }

    // 模拟某个goroutine出现异常
    go func() {
        time.Sleep(500 * time.Millisecond)
        fmt.Println("simulating an error in a goroutine")
        cancel() // 取消所有goroutine
    }()

    time.Sleep(1000 * time.Millisecond)
}