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

前端之家收集整理的这篇文章主要介绍了为什么我的Golang频道会永远阻止写入?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在过去的几天里,我一直试图通过重构我的一个命令行实用程序来解决Golang的并发问题,但我陷入了困境.

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

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

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

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

这是代码的相关部分:

  1. // Given an issue,determine if it has an open comment
  2. // Returns true if there is an open comment on the issue,otherwise false
  3. func getAndProcessComments(issue Issue,channel chan<- Issue,wg *sync.WaitGroup) {
  4. // Decrement the wait counter when the function returns
  5. defer wg.Done()
  6.  
  7. needsReply := false
  8.  
  9. // Loop over the comments in the issue
  10. for _,comment := range issue.Fields.Comment.Comments {
  11. commentMatched,err := regexp.MatchString("~"+config.JIRAUsername,comment.Body)
  12. checkError("Failed to regex match against comment body",err)
  13.  
  14. if commentMatched {
  15. needsReply = true
  16. }
  17.  
  18. if comment.Author.Name == config.JIRAUsername {
  19. needsReply = false
  20. }
  21. }
  22.  
  23. // Only add the issue to the channel if it needs a reply
  24. if needsReply == true {
  25. // This never allows the defered wg.Done() to execute?
  26. channel <- issue
  27. }
  28. }
  29.  
  30. func main() {
  31. start := time.Now()
  32.  
  33. // This retrieves all issues in a search from JIRA
  34. allIssues := getFullIssueList()
  35.  
  36. // Initialize a wait group
  37. var wg sync.WaitGroup
  38.  
  39. // Set the number of waits to the number of issues to process
  40. wg.Add(len(allIssues))
  41.  
  42. // Create a channel to store issues that need a reply
  43. channel := make(chan Issue)
  44.  
  45. for _,issue := range allIssues {
  46. go getAndProcessComments(issue,channel,&wg)
  47. }
  48.  
  49. // Block until all of my goroutines have processed their issues.
  50. wg.Wait()
  51.  
  52. // Only send an email if the channel has one or more issues
  53. if len(channel) > 0 {
  54. sendEmail(channel)
  55. }
  56.  
  57. fmt.Printf("Script ran in %s",time.Since(start))
  58. }
goroutines阻止发送到无缓冲的通道.
解决goroutines的最小变化是创建一个缓冲通道,其容量适用于所有问题:
  1. channel := make(chan Issue,len(allIssues))

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

猜你在找的Go相关文章