【发布时间】:2014-08-18 00:26:51
【问题描述】:
我正在尝试将 PHP 的一个简单同步位移植到 Go,但我很难理解并发性在通道方面是如何工作的。 PHP 脚本请求获取媒体库部分的列表,然后请求获取每个部分中的项目。如果该部分是电视节目列表,则它会请求每个节目获取所有季节,然后另一个请求获取每个季节内的剧集。
我正在尝试在 pidgeon-go 中编写我期望的工作,但我没有任何运气。我在网上尝试了各种频道指南,但通常会出现死锁警告。目前,此示例警告 item :=
package main
import (
"fmt"
"time"
)
// Get all items for all sections
func 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 sections
func getSections() []string {
return []string{"HD Movies", "Movies", "TV Shows"}
}
// Get items within the given section, note that some items may spawn sub-items
func 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 parent
func getSubItemsForItem(name string, ch chan string) {
time.Sleep(1 * time.Second)
ch <- name + ": S01E01"
ch <- name + ": S01E02"
}
【问题讨论】:
标签: concurrency go