首頁 > 後端開發 > Golang > 主體

從 goroutine 讀取多個回傳值

PHPz
發布: 2024-02-09 12:30:09
轉載
1053 人瀏覽過

从 goroutine 读取多个返回值

php小編蘋果從goroutine讀取多個回傳值是Go語言中的常見操作。 Goroutine是Go語言中的輕量級線程,能夠實現並發執行。在某些情況下,我們需要從一個或多個goroutine中取得返回值,以便進一步處理。這種操作可以透過使用通道(channel)來實現,通道是goroutine之間進行通訊的重要機制。透過通道,我們可以在goroutine之間傳遞數據,實現協程之間的同步與通訊。在本文中,我們將詳細介紹如何從goroutine讀取多個傳回值的技巧和注意事項。

問題內容

我正在嘗試用 Go 編寫 wc(1),並且正在嘗試使用 goroutine 來更有效地計算大量輸入檔。我的程式碼工作正常,但我很難實作一種方法來總結所有 go 例程的統計資料。如何將函數變數 nlnwnc 傳遞給 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 變量,並且在迭代所有結果時,只需將nlncnw 的結果會加到該總變數中。

<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中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!