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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

檢查同步通道是否準(zhǔn)備就緒

檢查同步通道是否準(zhǔn)備就緒

Go
繁星點(diǎn)點(diǎn)滴滴 2021-10-25 18:17:33
我想知道,如果去語(yǔ)言允許檢查多渠道正準(zhǔn)備在同一時(shí)間。這是我正在嘗試做的一個(gè)有點(diǎn)人為的例子。(實(shí)際原因是看能否在go中原生實(shí)現(xiàn)petrinet)package mainimport "fmt"func mynet(a, b, c, d <-chan int, res chan<- int) {    for {        select {        case v1, v2 := <-a, <-b:            res <- v1+v2        case v1, v2 := <-c, <-d:            res <- v1-v2        }    }}func main() {        a := make(chan int)        b := make(chan int)        c := make(chan int)        d := make(chan int)        res := make(chan int, 10)        go mynet(a, b, c, d, res)        a <- 5        c <- 5        d <- 7        b <- 7        fmt.Println(<-res)        fmt.Println(<-res)}這不會(huì)如圖所示編譯。它可以通過(guò)只檢查一個(gè)通道來(lái)編譯,但是如果該通道準(zhǔn)備好而另一個(gè)通道沒(méi)有準(zhǔn)備好,它可能會(huì)很容易死鎖。package mainimport "fmt"func mynet(a, b, c, d <-chan int, res chan<- int) {    for {        select {        case v1 := <-a:            v2 := <-b            res <- v1+v2        case v1 := <-c:            v2 := <-d            res <- v1-v2        }    }}func main() {        a := make(chan int)        b := make(chan int)        c := make(chan int)        d := make(chan int)        res := make(chan int, 10)        go mynet(a, b, c, d, res)        a <- 5        c <- 5        d <- 7        //a <- 5        b <- 7        fmt.Println(<-res)        fmt.Println(<-res)}在一般情況下,我可能有多個(gè)案例在同一個(gè)頻道上等待,例如case v1, v2 := <-a, <-b:...case v1, v2 := <-a, <-c:...所以當(dāng)一個(gè)值在通道 a 上準(zhǔn)備好時(shí),我不能提交到任何一個(gè)分支:只有當(dāng)所有值都準(zhǔn)備好時(shí)。
查看完整描述

2 回答

?
慕雪6442864

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊

您不能同時(shí)在多個(gè)頻道上進(jìn)行選擇。您可以做的是實(shí)現(xiàn)一個(gè)扇入模式,以合并來(lái)自多個(gè)渠道的值。


基于您的代碼的粗略示例可能如下所示:


func collect(ret chan []int, chans ...<-chan int) {

    ints := make([]int, len(chans))

    for i, c := range chans {

        ints[i] = <-c

    }

    ret <- ints

}


func mynet(a, b, c, d <-chan int, res chan<- int) {

    set1 := make(chan []int)

    set2 := make(chan []int)

    go collect(set1, a, b)

    go collect(set2, c, d)

    for {

        select {

        case vs := <-set1:

            res <- vs[0] + vs[1]

        case vs := <-set2:

            res <- vs[0] + vs[1]

        }

    }

}


查看完整回答
反對(duì) 回復(fù) 2021-10-25
  • 2 回答
  • 0 關(guān)注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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