Go並發編程模型:pipeline和cancellation

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

本文是Go Concurrency Patterns: Pipelines and cancellation的讀書筆記:

(1)Pipeline定義:

What is a pipeline?

There’s no formal definition of a pipeline in Go; it’s just one of many kinds of concurrent programs. Informally, a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function. In each stage, the goroutines

receive values from upstream via inbound channels
perform some function on that data, usually producing new values
send values downstream via outbound channels

Each stage has any number of inbound and outbound channels, except the first and last stages, which have only outbound or inbound channels, respectively. The first stage is sometimes called the source or producer; the last stage, the sink or consumer.

在Go並發編程中,pipeline由一系列stage組成,而每個stage則由一組執行相同功能的goroutine組成,各個stage之間通過channel進行通訊。goroutine從inbound channels從上遊stage接收訊息,經過一番處理後,利用outbound channels向下遊stage發送訊息。每個stage可以包含若干個inbound和outbound channels,但是第一個stage只能有一個outbound channel,最後一個stage只能有一個inbound channel。

(2)一個基本的pipeline例子:

package mainimport "fmt"func gen(nums ...int) <-chan int {    out := make(chan int)    go func() {        for _, n := range nums {            out <- n        }        close(out)    }()    return out}func sq(in <-chan int) <-chan int {    out := make(chan int)    go func() {        for n := range in {            out <- n * n        }        close(out)    }()    return out}func main() {    // Set up the pipeline.    c := gen(2, 3)    out := sq(c)    // Consume the output.    fmt.Println(<-out) // 4    fmt.Println(<-out) // 9}

執行結果:

49

gen()是第一個stage併產生一個outbound channel。sq()是第二個stage,從gen()的outbound channel接受輸入,併產生一個新的outbound channel,把每個數的平方發送到這個outbound channel中。main()是最後一個stage,接收sq()的outbound channel的輸入,並把結果列印出來。

(3)fan-out和fan-in
Fan-out和fan-in的定義:

Multiple functions can read from the same channel until that channel is closed; this is called fan-out. This provides a way to distribute work amongst a group of workers to parallelize CPU use and I/O.

A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that’s closed when all the inputs are closed. This is called fan-in.

多個函數從同一個channel讀取叫fan-out;一個函數從多個channel讀取並把處理結果發送到一個channel中,稱之為fan-in。舉例如下:

package mainimport (    "fmt"    "sync")func gen(nums ...int) <-chan int {    out := make(chan int)    go func() {        for _, n := range nums {            out <- n        }        close(out)    }()    return out}func sq(in <-chan int) <-chan int {    out := make(chan int)    go func() {        for n := range in {            out <- n * n        }        close(out)    }()    return out}func merge(cs ...<-chan int) <-chan int {    var wg sync.WaitGroup    out := make(chan int)    // Start an output goroutine for each input channel in cs.  output    // copies values from c to out until c is closed, then calls wg.Done.    output := func(c <-chan int) {        for n := range c {            out <- n        }        wg.Done()    }    wg.Add(len(cs))    for _, c := range cs {        go output(c)    }    // Start a goroutine to close out once all the output goroutines are    // done.  This must start after the wg.Add call.    go func() {        wg.Wait()        close(out)    }()    return out}func main() {    in := gen(2, 3)    // Distribute the sq work across two goroutines that both read from in.    c1 := sq(in)    c2 := sq(in)    // Consume the merged output from c1 and c2.    for n := range merge(c1, c2) {        fmt.Println(n) // 4 then 9, or 9 then 4    }}

以下代碼稱之為fan-out:

// Distribute the sq work across two goroutines that both read from in.c1 := sq(in)c2 := sq(in)

而merge函數的工作即為fan-in。

(3)通知上遊stage取消發送操作。例子如下:

package mainimport (    "fmt"    "sync")func gen(done <-chan struct{}, nums ...int) <-chan int {    out := make(chan int)    go func() {        defer close(out)        for _, n := range nums {            select {            case out <- n:            case <- done:                return            }        }    }()    return out}func sq(done <-chan struct{}, in <-chan int) <-chan int {    out := make(chan int)    go func() {        defer close(out)        for n := range in {            select {            case out <- n * n:            case <-done:                return            }        }    }()    return out}func merge(done <-chan struct{}, cs ...<-chan int) <-chan int {    var wg sync.WaitGroup    out := make(chan int)    // Start an output goroutine for each input channel in cs.  output    // copies values from c to out until c or done is closed, then calls    // wg.Done.    output := func(c <-chan int) {        defer wg.Done()        for n := range c {            select {            case out <- n:            case <-done:                return            }        }    }    wg.Add(len(cs))    for _, c := range cs {        go output(c)    }    // Start a goroutine to close out once all the output goroutines are    // done.  This must start after the wg.Add call.    go func() {        wg.Wait()        close(out)    }()    return out}func main() {    // Set up a done channel that's shared by the whole pipeline,    // and close that channel when this pipeline exits, as a signal    // for all the goroutines we started to exit.    done := make(chan struct{})    defer close(done)    in := gen(done, 2, 3)    // Distribute the sq work across two goroutines that both read from in.    c1 := sq(done, in)    c2 := sq(done, in)    // Consume the first value from output.    out := merge(done, c1, c2)    fmt.Println(<-out) // 4 or 9}

構建一個done channel,調用close函數關閉done channel,用來通知上遊stage停止發送。

(4)Pipeline構建的原則:

Here are the guidelines for pipeline construction:

stages close their outbound channels when all the send operations are done.
stages keep receiving values from inbound channels until those channels are closed or the senders are unblocked.

Pipelines unblock senders either by ensuring there’s enough buffer for all the values that are sent or by explicitly signalling senders when the receiver may abandon the channel.

本文是Go Concurrency Patterns: Pipelines and cancellation的讀書筆記:

(1)Pipeline定義:

What is a pipeline?

There’s no formal definition of a pipeline in Go; it’s just one of many kinds of concurrent programs. Informally, a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function. In each stage, the goroutines

receive values from upstream via inbound channels
perform some function on that data, usually producing new values
send values downstream via outbound channels

Each stage has any number of inbound and outbound channels, except the first and last stages, which have only outbound or inbound channels, respectively. The first stage is sometimes called the source or producer; the last stage, the sink or consumer.

在Go並發編程中,pipeline由一系列stage組成,而每個stage則由一組執行相同功能的goroutine組成,各個stage之間通過channel進行通訊。goroutine從inbound channels從上遊stage接收訊息,經過一番處理後,利用outbound channels向下遊stage發送訊息。每個stage可以包含若干個inbound和outbound channels,但是第一個stage只能有一個outbound channel,最後一個stage只能有一個inbound channel。

(2)一個基本的pipeline例子:

package mainimport "fmt"func gen(nums ...int) <-chan int {    out := make(chan int)    go func() {        for _, n := range nums {            out <- n        }        close(out)    }()    return out}func sq(in <-chan int) <-chan int {    out := make(chan int)    go func() {        for n := range in {            out <- n * n        }        close(out)    }()    return out}func main() {    // Set up the pipeline.    c := gen(2, 3)    out := sq(c)    // Consume the output.    fmt.Println(<-out) // 4    fmt.Println(<-out) // 9}

執行結果:

49

gen()是第一個stage併產生一個outbound channel。sq()是第二個stage,從gen()的outbound channel接受輸入,併產生一個新的outbound channel,把每個數的平方發送到這個outbound channel中。main()是最後一個stage,接收sq()的outbound channel的輸入,並把結果列印出來。

(3)fan-out和fan-in
Fan-out和fan-in的定義:

Multiple functions can read from the same channel until that channel is closed; this is called fan-out. This provides a way to distribute work amongst a group of workers to parallelize CPU use and I/O.

A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that’s closed when all the inputs are closed. This is called fan-in.

多個函數從同一個channel讀取叫fan-out;一個函數從多個channel讀取並把處理結果發送到一個channel中,稱之為fan-in。舉例如下:

package mainimport (    "fmt"    "sync")func gen(nums ...int) <-chan int {    out := make(chan int)    go func() {        for _, n := range nums {            out <- n        }        close(out)    }()    return out}func sq(in <-chan int) <-chan int {    out := make(chan int)    go func() {        for n := range in {            out <- n * n        }        close(out)    }()    return out}func merge(cs ...<-chan int) <-chan int {    var wg sync.WaitGroup    out := make(chan int)    // Start an output goroutine for each input channel in cs.  output    // copies values from c to out until c is closed, then calls wg.Done.    output := func(c <-chan int) {        for n := range c {            out <- n        }        wg.Done()    }    wg.Add(len(cs))    for _, c := range cs {        go output(c)    }    // Start a goroutine to close out once all the output goroutines are    // done.  This must start after the wg.Add call.    go func() {        wg.Wait()        close(out)    }()    return out}func main() {    in := gen(2, 3)    // Distribute the sq work across two goroutines that both read from in.    c1 := sq(in)    c2 := sq(in)    // Consume the merged output from c1 and c2.    for n := range merge(c1, c2) {        fmt.Println(n) // 4 then 9, or 9 then 4    }}

以下代碼稱之為fan-out:

// Distribute the sq work across two goroutines that both read from in.c1 := sq(in)c2 := sq(in)

而merge函數的工作即為fan-in。

(3)通知上遊stage取消發送操作。例子如下:

package mainimport (    "fmt"    "sync")func gen(done <-chan struct{}, nums ...int) <-chan int {    out := make(chan int)    go func() {        defer close(out)        for _, n := range nums {            select {            case out <- n:            case <- done:                return            }        }    }()    return out}func sq(done <-chan struct{}, in <-chan int) <-chan int {    out := make(chan int)    go func() {        defer close(out)        for n := range in {            select {            case out <- n * n:            case <-done:                return            }        }    }()    return out}func merge(done <-chan struct{}, cs ...<-chan int) <-chan int {    var wg sync.WaitGroup    out := make(chan int)    // Start an output goroutine for each input channel in cs.  output    // copies values from c to out until c or done is closed, then calls    // wg.Done.    output := func(c <-chan int) {        defer wg.Done()        for n := range c {            select {            case out <- n:            case <-done:                return            }        }    }    wg.Add(len(cs))    for _, c := range cs {        go output(c)    }    // Start a goroutine to close out once all the output goroutines are    // done.  This must start after the wg.Add call.    go func() {        wg.Wait()        close(out)    }()    return out}func main() {    // Set up a done channel that's shared by the whole pipeline,    // and close that channel when this pipeline exits, as a signal    // for all the goroutines we started to exit.    done := make(chan struct{})    defer close(done)    in := gen(done, 2, 3)    // Distribute the sq work across two goroutines that both read from in.    c1 := sq(done, in)    c2 := sq(done, in)    // Consume the first value from output.    out := merge(done, c1, c2)    fmt.Println(<-out) // 4 or 9}

構建一個done channel,調用close函數關閉done channel,用來通知上遊stage停止發送。

(4)Pipeline構建的原則:

Here are the guidelines for pipeline construction:

stages close their outbound channels when all the send operations are done.
stages keep receiving values from inbound channels until those channels are closed or the senders are unblocked.

Pipelines unblock senders either by ensuring there’s enough buffer for all the values that are sent or by explicitly signalling senders when the receiver may abandon the channel.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.