簡體   English   中英

為什么我的Golang頻道會永遠阻止寫入?

[英]Why is my Golang Channel Write Blocking Forever?

在過去的幾天里,我一直試圖通過重構我的一個命令行實用程序來解決Golang的並發問題,但我陷入了困境。

這是原始代碼(主分支)。

這是具有並發性的分支(x_concurrent分支)。

當我使用go run jira_open_comment_emailer.go執行並發代碼時,如果將JIRA問題添加到此處的通道,則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))
}

goroutines阻止發送到無緩沖的通道。 解決goroutines的最小變化是創建一個緩沖通道,其容量適用於所有問題:

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

並在調用wg.Wait()后關閉通道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM