第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang字符串通道發(fā)送/接收不一致

golang字符串通道發(fā)送/接收不一致

Go
泛舟湖上清波郎朗 2021-11-08 19:34:08
新去。我正在使用 1.5.1。我正在嘗試根據傳入頻道累積一個單詞列表。但是,我的輸入通道 (wdCh) 在測試期間有時會得到空字符串 ("")。我很困惑。在將其累積計數添加到我的地圖之前,我寧愿不對空字符串進行測試。對我來說感覺就像一個黑客。package accumulatorimport (    "fmt"    "github.com/stretchr/testify/assert"    "testing")var words map[string]intfunc Accumulate(wdCh chan string, closeCh chan bool) {    words = make(map[string]int)    for {        select {        case word := <-wdCh:            fmt.Printf("word = %s\n", word)            words[word]++        case <-closeCh:            return        }    }}func pushWords(w []string, wdCh chan string) {    for _, value := range w {        fmt.Printf("sending word = %s\n", value)        wdCh <- value    }    close(wdCh)}func TestAccumulate(t *testing.T) {    sendWords := []string{"one", "two", "three", "two"}    wMap := make(map[string]int)    wMap["one"] = 1    wMap["two"] = 2    wMap["three"] = 1    wdCh := make(chan string)    closeCh := make(chan bool)    go Accumulate(wdCh, closeCh)    pushWords(sendWords, wdCh)    closeCh <- true    close(closeCh)    assert.Equal(t, wMap, words)}
查看完整描述

2 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

查看這篇關于channel-axioms 的文章。看起來在關閉wdCh和在closeCh通道上發(fā)送 true之間存在競爭。

因此,結果取決于在pushWords返回 和之間首先安排什么Accumulate。

如果TestAccumulate首先運行,則發(fā)送 true on closeCh,然后在Accumulate運行時它會選擇兩個通道中的任何一個,因為它們都可以運行,因為pushWordsclosed wdCh

來自關閉通道的接收立即返回零值。

直到closedCh發(fā)出信號,Accumulate會在地圖中隨機放置一個或多個空“”字。

如果Accumulate首先運行,那么它可能會在單詞映射中放入許多空字符串,因為它會循環(huán)直到TestAccumulate運行并最終在 上發(fā)送信號closeCh

一個簡單的解決方法是移動

close(wdCh)

發(fā)送后truecloseCh。這種方式wdCh不能返回零值,直到您在closeCh. 此外,closeCh <- true塊因為closeCh沒有緩沖區(qū)大小,所以wdCh在你保證Accumulate永遠完成循環(huán)之前不會關閉。


查看完整回答
反對 回復 2021-11-08
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

我認為原因是當您關閉通道時,“選擇”雖然會收到信號。


因此,當您關閉“func pushWords”中的“wdCh”時,Accumulate 中的循環(huán)將從“<-wdCh”接收信號??赡苁悄銘撎砑右恍┐a來測試通道關閉后的動作!


for {

    select {

    case word, ok := <-wdCh:

        if !ok {

            fmt.Println("channel wdCh is closed!")

            continue

        }

        fmt.Printf("word = %s\n", word)

        words[word]++

    case <-closeCh:

        return

    }

}


查看完整回答
反對 回復 2021-11-08
  • 2 回答
  • 0 關注
  • 300 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號