GoLang學習 -- goroutine使用指南

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

並發是golang最有核心競爭力的功能,golang的並發依賴的並不是線程,而是協程。協程和線程有什麼區別呢?最大的區別就是協程比線程更為輕量。預設情況中一個進程最大可以啟動254個線程,這個數值也可以改為無限制,但主機資源消耗就會非常嚴重。而使用協程就不同了,一個進程可以輕輕鬆鬆啟動上萬個協程而毫無壓力。

因此本篇文章就來說說在golang中如何建立使用協程。

golang設計協程的目的,一方面是為了提高並發效率,另外一方面就是儘可能發揮多核CPU的能力。golang內建的調度器,可以讓多核CPU中每個CPU執行一個協程。通過這樣的設計,把每個CPU都充分調動起來,減少CPU空閑時間,提高了CPU輸送量,無形當中也提高了I/O效率。

提到golang的協程,就不得不提到一個名詞:管道(pipeline)。這裡的管道和Linux系統中的pipe不是同一個意思,這裡的管道指的是使用channel將多個處理步驟相連,形成的具有多級channel的資料流。一般來說,管道都是通過流入口讀取資料,從流出口發送資料,讀取資料之後都會調用某些函數來處理這些資料。

管道中的每一級都可以擁有多個流入口和流出口,但管道的首級和末級一般情況只有一個流入口或者流出口。擁有流出口的首級一般稱之為資料來源或者生產者,擁有流入口的末級一般稱之為終點或者消費者。

這些技術解釋,看上去很枯燥,我們通過一些簡單的執行個體逐漸深入講解。首先看下面的執行個體。在這個執行個體中,共分有三步來處理資料,第一步gen函數負責將傳入的資料放到channel之中,當資料傳完之後,關閉channel。代碼如下:

func gen(nums ...int) <-chan int {    out := make(chan int)    go func() {        for _, n := range nums {            out <- n        }        close(out)    }()    return out}

第二步,sq函數從channel中讀取資料,並對每個數值進行相乘運算,然後再將運算後的資料發送到下一個channel當中。代碼如下:

func sq(in <-chan int) <-chan int {    out := make(chan int)    go func() {        for n := range in {            out <- n * n        }        close(out)    }()    return out}

最後一步,就是main函數了。main函數接受二階段中發送的資料,然後輸出這些資料知道channel關閉。代碼如下:

func main() {    // Set up the pipeline.    c := gen(2, 3)    out := sq(c)    // Consume the output.    fmt.Println(<-out) // 4    fmt.Println(<-out) // 9}

因為sq函數的參數類型和傳回型別一致,所以sq函數可以合并處理,修改後的代碼如下:

func main() {    // Set up the pipeline and consume the output.    for n := range sq(sq(gen(2, 3))) {        fmt.Println(n) // 16 then 81    }}

到這裡,以上三步就完成了一個非常基本的golang並行存取模型。但還存在很多缺陷,我們繼續對它進行最佳化。首先第一步,就是將每一步處理單個channel,改為處理多個channel。

在golang並行存取模型中,存在兩個概念:Fan-in(扇入)和Fan-out(扇出)。扇入指的是一個程式可以同時從多個channel中讀取資料並且對其進行處理,直到收到明確的停止訊號或者所有的channel被關閉。
扇出指的是多個程式可以同時從一個channel中讀取資料並且對其進行處理,直到channel關閉。扇出值越大,CPU利用率越高,IO使用率也就越高。

下面的最佳化,就是針對扇入和扇出入手的。

我們將調用一次sq函數變為調用兩次sq函數,同時引入一個merge函數來扇入處理結果資料。

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

merge函數會通過啟動一個協程將多個channel中的資料合併到一個channel之中。Golang語言中,向一個已經關閉的channel中發送資料會引發一個運行時異常,所以有必要在發送資料之前需要確保channel未被關閉。這裡,我們使用sync.WaitGroup 做同步,只有資料發送完了,才會關閉channel。

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}

現在我們已經有了一個這樣的模型:

  • 只有所有的資料都發送完成之後,才會關閉channel
  • 其它協程會一直接受資料,直到所有channel被關閉。

通過這個模型,我們可以迴圈接受並且處理資料。但我們的腳步不會就此停止,讓我們繼續往下最佳化。

目前所有的協程都是獨立啟動並執行,負責發送的協程可以不停的發送資料,接受資料的協程會不停的接受資料。那如果接受資料的協程不再需要這些資料了,那麼又該如何通知上遊的協程呢?

在上面的樣本中,如果某一個階段發生異常而退出,那麼其他協程無法獲知這個事件,就會發生一些資源泄漏。

    // Consume the first value from output.    out := merge(c1, c2)    fmt.Println(<-out) // 4 or 9    return    // Since we didn't receive the second value from out,    // one of the output goroutines is hung attempting to send it.}

所以下一步最佳化的方向就是協程之間的協同工作。先拿channel開刀,因為channel是可以帶緩衝的。所以我們聲明一個帶有緩衝的channel:

c := make(chan int, 2) // buffer size 2c <- 1  // succeeds immediatelyc <- 2  // succeeds immediatelyc <- 3  // blocks until another goroutine does <-c and receives 1

channel的buffer是2,所以一次只能放入兩個值,只有這兩個值被處理了之後才能繼續往裡面放入新值。

這樣,我們就可以修改一個gen函數。

func gen(nums ...int) <-chan int {    out := make(chan int, len(nums))    for _, n := range nums {        out <- n    }    close(out)    return out}

回到merge函數中,我們也可以考慮在merge函數中使用一個帶有緩衝的channel:

func merge(cs ...<-chan int) <-chan int {    var wg sync.WaitGroup    out := make(chan int, 1) // enough space for the unread inputs    // ... the rest is unchanged ...

直接聲明一個buffer=1的channel,不是一個好主意。因為目前這個值是已知的,但以後如果發生變化,那麼還要修改代碼,所以最好寫成通用代碼。但現在先這樣用著吧。

這些貌似和協同工作,沒關係。那下面就是有關係的代碼了,加入main函數中準備要退出了,也就是不再接受資料了。main函數需要通知上遊的協程停止發送資料,main函數如何做到這點呢?

main函數使用另外一個channel來完成這件事情,當需要退出時,main就通過done這個新增的channel發送訊息,如下:

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 first value from output.    done := make(chan struct{}, 2)    out := merge(done, c1, c2)    fmt.Println(<-out) // 4 or 9    // Tell the remaining senders we're leaving.    done <- struct{}{}    done <- struct{}{}}

main給done發送了一個空的結構體,但這個沒有關係,我們關心的是done裡面是否有值,而不是有什麼值。其它協程如果需要接受訊號,那麼就需要使用select來處理done。

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 is closed or it receives a value    // from done, then output calls wg.Done.    output := func(c <-chan int) {        for n := range c {            select {            case out <- n:            case <-done:            }        }        wg.Done()    }    // ... the rest is unchanged ...

這種方法雖然可以實現通知的目的,但還有問題:main函數需要明確知道一共有多少個協程需要通知到,因此done <- struct{}{}需要不停的調用,直到所有的協程都被通知到位。如果有一些協程沒有被通知到,呵呵,等著看異常吧。

為瞭解決這個問題,我們通過關閉done的方式來通知所有的協程。因為從一個已經關閉的channel中接受資料,會使當前協程立即退出。所以main函數中關閉了done,那麼所有等待著從done接受關閉訊號的協程們,會老老實實的自動結束。

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 will be closed by the deferred call.}

這樣,merge函數就可以明確得知其下遊已經不再需要處理資料了,merge就可以放心退出了。而sq也可以通過得知done已經關閉,而不再向外發送資料了。但這些函數再退出之時都會調用wg.Done來告訴main,它們都已經合法退出。

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            }        }    }    // ... the rest is unchanged ...
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}

到這裡,才算是真正的完成了協程之間的協同工作。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。原文請關注http://blog.csdn.net/vikings_1001

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.