【问题标题】:Multiple concurrency in golanggolang中的多并发
【发布时间】: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


    【解决方案1】:

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

    现在的问题是你要么必须关闭通道,要么在 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

    【讨论】:

    • 谢谢。完成后等待和关闭频道的最佳方式是什么?这些请求可能会花费不可预测的时间。我尝试了 WaitGroup,但它警告所有 goroutines 都处于睡眠状态。
    • 我想通了,我只需要将 WaitGroup.Done() 移到监听 goroutine 之后。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 2020-06-17
    相关资源
    最近更新 更多