【发布时间】:2016-09-23 05:07:45
【问题描述】:
在过去的几天里,我一直试图通过重构我的一个命令行实用程序来尝试在 Golang 中的并发性,但我被卡住了。
Here's原代码(master分支)。
Here's并发分支(x_concurrent 分支)。
当我使用go run jira_open_comment_emailer.go 执行并发代码时,如果将JIRA 问题添加到here 频道,defer 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))
}
【问题讨论】:
-
您到处都有
len(channel),但该频道没有长度,因为它没有缓冲。您需要从通道接收以完成任何发送(通常,根据缓冲通道的长度做出决策是错误的,因为并发操作可能会竞相更改该值) -
所以,如果我正在对通道进行所有写入,等待它们完成,然后从通道读取......这永远不会发生,因为发送永远不会真正完成并且触发
defer wg.Done()?一般来说,您将如何解决实现这种并发性的问题?另外,我不确定您在len(channel)上是否正确,因为 godocs 声明它返回通道中当前的元素数量,而不是像cap(channel)这样的容量。 golang.org/pkg/builtin/#len -
len(channel)返回“缓冲”通道中的当前项目数,但由于通道通常是同时使用的,所以len的结果一读到它就“过时”。通常会有并发的 goroutine 从通道发送和接收。我建议再次浏览 Tour Of Go 中的 Concurrency 部分,以更好地了解频道的工作原理。 -
@s_dolan 是的,第一个通道发送将阻塞,直到有人读取它,这永远不会发生。您可以做的最简单的事情是启动一个 goroutine,它在 写入之前从通道的另一端读取。至于 len 和 cap,请考虑
len(c)始终 cap(c)。
标签: go concurrency channel