第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Goroutines 通道和“停止”

Goroutines 通道和“停止”

Go
Smart貓小萌 2021-12-06 17:13:18
我正在閱讀/工作Go Concurrency Patterns: Pipelines and cancel,但我無法理解停止短部分。我們有以下功能: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 gen(nums ...int) <-chan int {    out := make(chan int)    go func() {        for _, n := range nums {            out <- n        }        close(out)    }()    return out}func merge(cs ...<-chan int) <-chan int {    var wg sync.WaitGroup    out := make(chan int, 1) // enough space for the unread inputs    // 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 first value from output.    out := merge(c1, c2)    fmt.Println(<-out) // 4 or 9    return    // Apparently if we had not set the merge out buffer size to 1    // then we would have a hanging go routine. }現(xiàn)在,如果您注意到 line 2in merge,它表示我們chan使用buffer大小為 1的 out ,因為這是未讀輸入的足夠空間。不過,我?guī)缀蹩梢钥隙ǎ覀儜?yīng)該分配chan與buffer大小2.根據(jù)此代碼示例:c := make(chan int, 2) // buffer size 2c <- 1  // succeeds immediatelyc <- 2  // succeeds immediatelyc <- 3  // blocks until another goroutine does <-c and receives 1 由于本節(jié)意味著一個chan的buffer大小3將不會阻止。任何人都可以澄清/幫助我理解嗎?
查看完整描述

1 回答

?
慕工程0101907

TA貢獻1887條經(jīng)驗 獲得超5個贊

程序向通道發(fā)送兩個值并從通道out讀取一個值out。未接收到其中一個值。

如果通道沒有緩沖(容量 0),那么其中一個發(fā)送 goroutine 將阻塞,直到程序退出。這是泄漏。

如果創(chuàng)建的通道容量為 1,則兩個 goroutine 都可以發(fā)送到通道并退出。發(fā)送到通道的第一個值由 接收main。第二個值保留在通道中。

如果 main 函數(shù)沒有從 channel 接收到一個值out,那么需要一個容量為 2 的 channel 來防止 goroutines 無限期地阻塞。



查看完整回答
反對 回復(fù) 2021-12-06
  • 1 回答
  • 0 關(guān)注
  • 192 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號