在过go 的几天里,我一直试图通过重构我的一个命令行实用程序来改变Golang中的并发性,但我被卡住了.

Here's原始代码(主分支).

Here's并发分支(x_并发分支).

当我使用go run jira_open_comment_emailer.go执行并发代码时,如果将JIRA问题添加到通道here,则defer wg.Done()永远不会执行,这会导致我的wg.Wait()永远挂起.

我的 idea 是,我有大量的JIRA问题,我想 for each 问题衍生一个goroutine,看看它是否有我需要回复的 comments .如果是的话,我想把它添加到某种 struct 中(经过一些研究,我 Select 了一个频道),我可以在以后像排队一样阅读,以建立一个邮箱提醒.

以下是代码的相关部分:

// Given an issue, determine if it has an open comment
// Returns true if there is an open comment on the issue, otherwise false
func getAndProcessComments(issue Issue, channel chan<- Issue, wg *sync.WaitGroup) {
    // Decrement the wait counter when the function returns
    defer wg.Done()

    needsReply := false

    // Loop over the comments in the issue
    for _, comment := range issue.Fields.Comment.Comments {
        commentMatched, err := regexp.MatchString("~"+config.JIRAUsername, comment.Body)
        checkError("Failed to regex match against comment body", err)

        if commentMatched {
            needsReply = true
        }

        if comment.Author.Name == config.JIRAUsername {
            needsReply = false
        }
    }

    // Only add the issue to the channel if it needs a reply
    if needsReply == true {
        // This never allows the defered wg.Done() to execute?
        channel <- issue
    }
}

func main() {
    start := time.Now()

    // This retrieves all issues in a search from JIRA
    allIssues := getFullIssueList()

    // Initialize a wait group
    var wg sync.WaitGroup

    // Set the number of waits to the number of issues to process
    wg.Add(len(allIssues))

    // Create a channel to store issues that need a reply
    channel := make(chan Issue)

    for _, issue := range allIssues {
        go getAndProcessComments(issue, channel, &wg)
    }

    // Block until all of my goroutines have processed their issues.
    wg.Wait()

    // Only send an email if the channel has one or more issues
    if len(channel) > 0 {
        sendEmail(channel)
    }

    fmt.Printf("Script ran in %s", time.Since(start))
}

推荐答案

大猩猩将挡路发送到无缓冲频道. 解锁goroutines的最小更改是创建一个容量可处理所有问题的缓冲通道:

channel := make(chan Issue, len(allIssues))

并在调用wg.Wait()之后关闭通道.

Go相关问答推荐

语法-for循环中的initit陈述是否允许分配?

带有条件的for循环中缺少RETURN语句

Go Colly-访问for循环中的URL

如何配置vscode以在Go中显示不必要的(过度指定的)泛型?

正确使用pgtype的方法

关于如何使用 Service Weaver 设置多个不同侦听器的问题

go测试10m后如何避免超时

如何在golang中使用viper获取对象的配置数组?

此 Golang 程序中的同步问题

golang中如何声明多个接口约束?

Golang 中具体类型的错误片段

有没有办法约束(通用)类型参数?

设置指向空接口的指针

go version -m 输出中的箭头符号=>是什么意思?

如何使用 go-playground/validator 编写 snake case 绑定标签?

处理程序后访问 HTTP 请求上下文

vs 代码调试 go 测试不通过标志

具有相同提前返回语句的函数的不同基准测试结果

泛型:对具有返回自身的函数的类型的约束

comparable和any有什么区别?