簡體   English   中英

在 Golang 中,如何使用 channel 處理多個 goroutine

[英]In Golang, how to handle many goroutines with channel

我想在 Golang 中使用 for 循環同時啟動 1000 個 goroutine。
問題是:我必須確保每個 goroutine 都已執行。
是否可以使用渠道來幫助我確定這一點?

結構有點像這樣:

func main {
    for i ... {
        go ...
        ch?
    ch?
}

正如@Andy 提到的,您可以使用sync.WaitGroup來實現這一點。 下面是一個例子。 希望代碼是不言自明的。

package main

import (
    "fmt"
    "sync"
    "time"
)

func dosomething(millisecs int64, wg *sync.WaitGroup) {
    defer wg.Done()
    duration := time.Duration(millisecs) * time.Millisecond
    time.Sleep(duration)
    fmt.Println("Function in background, duration:", duration)
}

func main() {
    arr := []int64{200, 400, 150, 600}
    var wg sync.WaitGroup
    for _, n := range arr {
     wg.Add(1)
     go dosomething(n, &wg)
    }
    wg.Wait()
    fmt.Println("Done")
}

我建議你遵循一個模式。 Concurrency 和 Channel 是好的,但是如果您以不好的方式使用它,您的程序可能會變得比預期的更慢。 處理多個 go-routine 和 channel 的簡單方法是通過工作池模式。

仔細看看下面的代碼

// In this example we'll look at how to implement
// a _worker pool_ using goroutines and channels.

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
    }
}

這個簡單的例子取自這里 此外, results通道可以幫助您跟蹤執行作業的所有 go 例程,包括失敗通知。

要確保 goroutine 完成並收集結果,請嘗試以下示例:

package main

import (
    "fmt"
)

const max = 1000

func main() {
    for i := 1; i <= max; i++ {
        go f(i)
    }

    sum := 0
    for i := 1; i <= max; i++ {
        sum += <-ch
    }

    fmt.Println(sum) // 500500
}

func f(n int) {
    // do some job here and return the result:
    ch <- n
}

var ch = make(chan int, max)

為了等待 1000 個 goroutines 完成,試試這個例子:

package main

import (
    "fmt"
    "sync"
)

func main() {
    wg := &sync.WaitGroup{}

    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go f(wg, i)
    }

    wg.Wait()
    fmt.Println("Done.")
}

func f(wg *sync.WaitGroup, n int) {
    defer wg.Done()
    fmt.Print(n, " ")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM