golang 使用协程和channel来实现工作池

/*
  go 工作池
  使用goroutine 和channeL来实现工作池
*/

package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan int, result chan<- int) {
    for j := range jobs {
        time.Sleep(time.Second)
        result <- j * 2
    }
}

func main() {
    /*
      为了使用我们的工作池 我们需要发送工作和接收结果的
    */
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    //
    for j := 1; j <= 9; j++ {
        jobs <- j
    }

    close(jobs)

    for a := 1; a <= 9; a++ {
        <-results
    }
}
 

你可能感兴趣的:(golang 使用协程和channel来实现工作池)