Golang在后端技术领域的重要性
2024-05-16

package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Printf("Worker %v start job %v
", id, j)
        time.Sleep(time.Second) // 模拟任务处理消耗时间
        fmt.Printf("Worker %v finish job %v
", id, j)
    // 将任务处理结果发送到results通道
        results <- j * 2
    }
}

func main() {
    numJobs := 5
    numWorkers := 3

    jobs := make(chan int, numJobs)
    results := make(chan int, numJobs)

    // 启动多个worker goroutine
    for w := 1; w <= numWorkers; w++ {
        go worker(w, jobs, results)
    }

    // 提交任务
    for j := 1; j <= numJobs; j++ {
        jobs <- j
    }

    // 关闭jobs通道,等待所有worker处理完任务
    close(jobs)

    // 获取所有任务处理结果
    for a := 1; a <= numJobs; a++ {
        <-results
    }
}
登录后复制