MST
星途 面试题库

面试题:Go 中如何实现简单的 Goroutine 负载均衡

在 Go 语言中,描述一种利用标准库实现简单的 Goroutine 负载均衡的方式,例如将一组任务平均分配到多个 Goroutine 中执行,简要说明实现思路并给出核心代码示例。
44.4万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 使用 sync.WaitGroup 来等待所有 Goroutine 完成任务。
  2. 将任务切片进行分割,分配给不同的 Goroutine。
  3. 利用 chan 来传递任务结果。

核心代码示例

package main

import (
    "fmt"
    "sync"
)

func worker(id int, tasks <-chan int, results chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    for task := range tasks {
        // 模拟任务处理
        result := task * 2 
        results <- result
    }
}

func main() {
    tasks := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    numWorkers := 3
    taskChan := make(chan int)
    resultChan := make(chan int)
    var wg sync.WaitGroup

    for i := 0; i < numWorkers; i++ {
        wg.Add(1)
        go worker(i, taskChan, resultChan, &wg)
    }

    go func() {
        for _, task := range tasks {
            taskChan <- task
        }
        close(taskChan)
    }()

    go func() {
        wg.Wait()
        close(resultChan)
    }()

    for result := range resultChan {
        fmt.Println("Result:", result)
    }
}

在上述代码中:

  1. worker 函数是每个 Goroutine 执行的任务逻辑,从 tasks 通道中接收任务,处理后将结果发送到 results 通道。
  2. main 函数中,创建了任务切片 tasks,并根据 numWorkers 创建了相应数量的 Goroutine 来处理任务。
  3. 使用 sync.WaitGroup 等待所有 Goroutine 完成任务,最后从 resultChan 通道中接收并打印任务结果。