MST

星途 面试题库

面试题:Go语言中Goroutine与WaitGroup及Mutex的复杂协作

假设有一个任务队列,里面有若干任务(可以用整数数组模拟,每个整数代表一个任务ID)。启动5个Goroutine从任务队列中取出任务并处理(处理可以简单打印任务ID和处理完成信息)。使用WaitGroup等待所有任务处理完成,同时使用Mutex保证任务队列的并发安全访问,防止多个Goroutine同时取到相同任务。请实现这个功能。
47.7万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
	"fmt"
	"sync"
)

func main() {
	taskQueue := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	var wg sync.WaitGroup
	var mu sync.Mutex
	workerCount := 5

	for i := 0; i < workerCount; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			for {
				mu.Lock()
				if len(taskQueue) == 0 {
					mu.Unlock()
					break
				}
				task := taskQueue[0]
				taskQueue = taskQueue[1:]
				mu.Unlock()

				fmt.Printf("Goroutine %d is processing task %d\n", id, task)
				fmt.Printf("Goroutine %d has finished processing task %d\n", id, task)
			}
		}(i)
	}

	wg.Wait()
}