为什么我的 Golang 通道写入永远阻塞?

Why is my Golang Channel Write Blocking Forever?

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

Here's原代码(master分支)

Here's并发分支(x_concurrent分支)。

当我用 go run jira_open_comment_emailer.go 执行并发代码时,如果 JIRA 问题被添加到频道 heredefer wg.Done() 永远不会执行,这导致我的 wg.Wait()永远挂着。

我的想法是,我有大量的 JIRA 问题,我想为每个问题分拆一个 goroutine,看看它是否有我需要回复的评论。如果是这样,我想将它添加到某个结构中(经过一些研究我选择了一个频道),我可以稍后像队列一样从中读取以建立电子邮件提醒。

这是代码的相关部分:

// 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 在发送到无缓冲通道时阻塞。 解除 goroutine 阻塞的最小更改是创建一个具有所有问题容量的缓冲通道:

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

并在调用 wg.Wait() 后关闭频道。