我正在嘗試將 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
- 1 回答
- 0 關(guān)注
- 276 瀏覽
添加回答
舉報
0/150
提交
取消