gpt4 book ai didi

concurrency - golang中的多并发

转载 作者:IT王子 更新时间:2023-10-29 01:43:08 24 4
gpt4 key购买 nike

我正在尝试将 PHP 的一个简单的同步位移植到 Go,但我很难理解并发如何与 channel 相关。 PHP 脚本请求获取媒体库部分列表,然后请求获取每个部分中的项目。如果该部分是电视节目列表,它会请求每个节目获取所有季节,然后另一个请求获取每个季节中的剧集。

我尝试在 pidgeon-go 中编写我期望的工作,但我没有任何运气。我在网上尝试过各种 channel 指南,但通常以死锁警告告终。目前这个例子警告 item := <-ch used as value 并且看起来不像是在等待 goroutines 返回。有人知道我能做什么吗?

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"

}

最佳答案

首先,该代码无法编译,因为 for item := <- ch应该是 for item := range ch

现在的问题是你要么必须关闭 channel ,要么在 goroutine 中永远运行你的循环。

go func() {
for {
item, ok := <-ch
if !ok {
break
}
fmt.Println(item)
items = append(items, item)

}
}()
time.Sleep(time.Second)
fmt.Println(items)

playground

关于concurrency - golang中的多并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25350945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com