为什么我的Golang频道会永远阻止写入?

为什么我的Golang频道会永远阻止写入?,第1张

概述在过去的几天里,我一直试图通过重构我的一个命令行实用程序来解决Golang的并发问题,但我陷入了困境. Here’s原始代码(master branch). Here’s具有并发性的分支(x_concurrent分支). 当我使用go run jira_open_comment_emailer.go执行并发代码时,如果将JIRA问题添加到通道here中,则延迟wg.Done()永远不会执行,这会导 在过去的几天里,我一直试图通过重构我的一个命令行实用程序来解决Golang的并发问题,但我陷入了困境.

Here’s原始代码(master branch).

Here’s具有并发性的分支(x_concurrent分支).

当我使用go run jira_open_comment_emailer.go执行并发代码时,如果将JIRA问题添加到通道here中,则延迟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 falsefunc 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阻止发送到无缓冲的通道.
解决goroutines的最小变化是创建一个缓冲通道,其容量适用于所有问题:
channel := make(chan Issue,len(allissues))

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

总结

以上是内存溢出为你收集整理的为什么我的Golang频道会永远阻止写入?全部内容,希望文章能够帮你解决为什么我的Golang频道会永远阻止写入?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1293720.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存