從 goroutine 讀取多個回傳值
Feb 09, 2024 pm 12:30 PM
go語言
php小編蘋果從goroutine讀取多個回傳值是Go語言中的常見操作。 Goroutine是Go語言中的輕量級線程,能夠實現並發執行。在某些情況下,我們需要從一個或多個goroutine中取得返回值,以便進一步處理。這種操作可以透過使用通道(channel)來實現,通道是goroutine之間進行通訊的重要機制。透過通道,我們可以在goroutine之間傳遞數據,實現協程之間的同步與通訊。在本文中,我們將詳細介紹如何從goroutine讀取多個傳回值的技巧和注意事項。
問題內容
我正在嘗試用 Go 編寫 wc(1),並且正在嘗試使用 goroutine 來更有效地計算大量輸入檔。我的程式碼工作正常,但我很難實作一種方法來總結所有 go 例程的統計資料。如何將函數變數 nl
、nw
、nc
傳遞給 main,並在所有 go 例程完成工作後在那裡匯總它們?
package main import ( "bufio" "fmt" "os" "strings" ) func main() { ch := make(chan string) for _, arg := range os.Args[1:] { go wc(arg, ch) } for range os.Args[1:] { fmt.Println(<-ch) } // Todo: summarize results... } func wc(arg string, ch chan<- string) { nl, nw, nc := 0, 0, 0 file, err := os.Open(arg) if err != nil { fmt.Println("Can't open file: %v", err) } defer file.Close() scan := bufio.NewScanner(file) for scan.Scan() { nl++ line := scan.Text() words := bufio.NewScanner(strings.NewReader(line)) words.Split(bufio.ScanWords) for words.Scan() { nw++ } runes := bufio.NewReader(strings.NewReader(line)) for { if _, _, err := runes.ReadRune(); err != nil { break } else { nc++ } } } ch <- fmt.Sprintf("%8d%8d%8d", nl, nw, nc+nl) }
登入後複製
解決方法
您已經接近答案了!我建議快速重構,返回帶有數字的 Result
對象,這將允許輕鬆地在末尾添加它們(而不是使用字串)。因此,您可以使用 chan 結果
而不是 chan string
。
基本上,您可以引入一個totalResult
變量,並且在迭代所有結果時,只需將nl
、nc
和nw
的結果會加到該總變數中。
<code>package main import ( "fmt" "math/rand" ) // define a struct to hold the result type Result struct { nl int nw int nc int } // this is to be able to use fmt.Println(result) func (r Result) String() string { return fmt.Sprintf("%8d%8d%8d", r.nl, r.nw, r.nc+r.nl) } func main() { ch := make(chan Result) for _, arg := range os.Args[1:] { go wc(arg, ch) } totalResult := Result{} for range os.Args[1:] { result := <-ch fmt.Println(result) // just for debugging // sum everything totalResult.nl += result.nl totalResult.nw += result.nw totalResult.nc += result.nc } fmt.Println("Total result:") fmt.Println(totalResult) } func wc(arg string, ch chan<- Result) { nl, nw, nc := 0, 0, 0 // your logic to compute nl, nw, nc goes here ch <- Result{nl: nl, nw: nw, nc: nc + nl} } </code>
登入後複製
您應該得到類似這樣的內容(包含 3 個檔案):
37 50 4753 19 106 821 47 255 3806 Total result: 103 411 9380
登入後複製
以上是從 goroutine 讀取多個回傳值的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)