MENU

Go实现一个简单的线程池

最近在学习Go语言,希望用它重写自己手头的项目。下面是用Go语言实现的一个简单线程池:

package main

import (
    "fmt"
    "time"
)

// 工作线程,处理具体的业务逻辑,将jobs中的任务取出,处理后将处理结果放置在results中
func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "processing job", j)
        time.Sleep(time.Second)
        results <- j * 2
    }
}

func main() {
    // 两个channel,一个用来放置工作项,一个用来存放处理结果
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    // 线程池中有三个线程
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    // 添加9个任务后关闭Channel
    for j := 1; j <= 9; j++ {
        jobs <- j
    }
    close(jobs)

    // 获取处理结果
    for a := 1; a <= 9; a++ {
        <-results
    }
}

运行结果:

worker 3 processing job 1
worker 2 processing job 2
worker 1 processing job 3
worker 1 processing job 4
worker 3 processing job 5
worker 2 processing job 6
worker 3 processing job 7
worker 1 processing job 8
worker 2 processing job 9
标签: Go
添加新评论