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

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

golang中的多并發(fā)

golang中的多并發(fā)

Go
三國紛爭 2021-08-10 15:58:15
我正在嘗試將 PHP 的一個簡單的同步位移植到 Go,但是我很難理解并發(fā)在通道方面是如何工作的。PHP 腳本請求獲取媒體庫部分的列表,然后請求獲取每個部分中的項目。如果該部分是電視節(jié)目列表,那么它會請求每個節(jié)目獲取所有季節(jié),然后另一個請求獲取每個季節(jié)內(nèi)的劇集。我已經(jīng)嘗試在 pidgeon-go 中編寫我期望的工作,但我沒有任何運氣。我在網(wǎng)上嘗試了各種頻道指南,但通常以死鎖警告告終。當(dāng)前,此示例警告 item := <-ch 用作值,并且看起來不像在等待 goroutines 返回。有沒有人知道我能做什么?package mainimport (    "fmt"    "time")// Get all items for all sectionsfunc main() {    ch := make(chan string)    sections := getSections()    for _, section := range sections {        go getItemsInSection(section, ch)    }    items := make([]string, 0)    for item := <- ch {        items = append(items, item)    }    fmt.Println(items)}// Return a list of the various library sectionsfunc getSections() []string {    return []string{"HD Movies", "Movies", "TV Shows"}}// Get items within the given section, note that some items may spawn sub-itemsfunc getItemsInSection(name string, ch chan string) {    time.Sleep(1 * time.Second)    switch name {    case "HD Movies":        ch <- "Avatar"        ch <- "Avengers"    case "Movies":        ch <- "Aliens"        ch <- "Abyss"    case "TV Shows":        go getSubItemsForItem("24", ch)        go getSubItemsForItem("Breaking Bad", ch)    }}// Get sub-items for a given parentfunc getSubItemsForItem(name string, ch chan string) {    time.Sleep(1 * time.Second)    ch <- name + ": S01E01"    ch <- name + ": S01E02"}
查看完整描述

1 回答

?
嚕嚕噠

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

首先,該代碼無法編譯,因為for item := <- ch應(yīng)該是for item := range ch


現(xiàn)在的問題是你要么必須關(guān)閉通道,要么在 goroutine 中永遠運行你的循環(huán)。


go func() {

    for {

        item, ok := <-ch

        if !ok {

            break

        }

        fmt.Println(item)

        items = append(items, item)


    }

}()

time.Sleep(time.Second)

fmt.Println(items)

playground


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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