MST

星途 面试题库

面试题:Go语言中context如何在父子goroutine间传递

在Go语言使用context管理请求生命周期场景下,假设存在一个父goroutine启动了若干子goroutine,简述如何将父goroutine的context传递给子goroutine,以实现对所有相关goroutine生命周期的统一管理,并给出一个简单示例代码。
21.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
  1. 传递方式简述:在Go语言中,将父goroutine的context传递给子goroutine,只需要在启动子goroutine时,将父context作为参数传递进去。这样,当父context被取消或超时,子goroutine可以通过context感知到,从而进行相应的清理操作并退出。
  2. 示例代码
package main

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

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    for i := 1; i <= 3; i++ {
        go childGoroutine(ctx, i)
    }

    time.Sleep(5 * time.Second)
    fmt.Println("Main goroutine is done")
}

在上述代码中:

  • main函数中创建了一个带有3秒超时的context,并通过cancel函数用于手动取消context
  • 启动了3个子goroutine,每个子goroutine接收父context
  • 子goroutine在循环中通过select监听ctx.Done()通道,当接收到取消信号时,打印信息并退出。