Go工作池實例

在這個例子中,我們將看看如何使用goroutineschannel實現一個工作池。

這裏是工作程序(worker),我們將運行幾個併發實例。這些工作程序(worker)將在工作渠道上接收工作,並將結果發送相應的結果。將每個工作程序(worker)睡一秒鐘,用來模擬執行的任務。

爲了使用工作程序(worker)池,需要向它們發送工作(或作業)並收集的結果。爲此做2個通道。

這啓動了3個工作程序(worker),最初被阻止,因爲還沒有作業。

然後,我們再發送5個作業,然後關閉該通道,以指示這是所有的工作。

最後,收集作業的所有結果。

運行程序顯示了5個作業正在由各種工作程序執行。該程序只需要約2秒的時間,儘管做了大約5秒的總工作,因爲有3個工作程序同時操作。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.com/go/go\_environment.html

timers.go的完整代碼如下所示 -

package main

import "fmt"
import "time"

// Here's the worker, of which we'll run several
// concurrent instances. These workers will receive
// work on the `jobs` channel and send the corresponding
// results on `results`. We'll sleep a second per job to
// simulate an expensive task.
func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "started  job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {

    // In order to use our pool of workers we need to send
    // them work and collect their results. We make 2
    // channels for this.
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    // This starts up 3 workers, initially blocked
    // because there are no jobs yet.
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    // Here we send 5 `jobs` and then `close` that
    // channel to indicate that's all the work we have.
    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    // Finally we collect all the results of the work.
    for a := 1; a <= 5; a++ {
        <-results
    }
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run worker-pools.go
worker 3 started  job 2
worker 1 started  job 1
worker 2 started  job 3
worker 3 finished job 2
worker 3 started  job 4
worker 1 finished job 1
worker 1 started  job 5
worker 2 finished job 3
worker 3 finished job 4
worker 1 finished job 5