目錄
問題內容
解決方法
首頁 後端開發 Golang 從 goroutine 讀取多個回傳值

從 goroutine 讀取多個回傳值

Feb 09, 2024 pm 12:30 PM
go語言

从 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 (
    &quot;fmt&quot;
    &quot;math/rand&quot;
)

// 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(&quot;%8d%8d%8d&quot;, 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 := &lt;-ch
        fmt.Println(result) // just for debugging

        // sum everything
        totalResult.nl += result.nl
        totalResult.nw += result.nw
        totalResult.nc += result.nc
    }

    fmt.Println(&quot;Total result:&quot;)
    fmt.Println(totalResult)
}

func wc(arg string, ch chan&lt;- Result) {
    nl, nw, nc := 0, 0, 0

    // your logic to compute nl, nw, nc goes here

    ch &lt;- 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 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章

倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章標籤

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

golang 如何使用反射存取私有欄位和方法 golang 如何使用反射存取私有欄位和方法 May 03, 2024 pm 12:15 PM

golang 如何使用反射存取私有欄位和方法

golang函數動態建立新函數的技巧 golang函數動態建立新函數的技巧 Apr 25, 2024 pm 02:39 PM

golang函數動態建立新函數的技巧

Go語言中的效能測試與單元測試的差異 Go語言中的效能測試與單元測試的差異 May 08, 2024 pm 03:09 PM

Go語言中的效能測試與單元測試的差異

Golang技術在設計分散式系統時應注意哪些陷阱? Golang技術在設計分散式系統時應注意哪些陷阱? May 07, 2024 pm 12:39 PM

Golang技術在設計分散式系統時應注意哪些陷阱?

Golang技術在機器學習中使用的函式庫和工具 Golang技術在機器學習中使用的函式庫和工具 May 08, 2024 pm 09:42 PM

Golang技術在機器學習中使用的函式庫和工具

golang函數命名約定的演變 golang函數命名約定的演變 May 01, 2024 pm 03:24 PM

golang函數命名約定的演變

Golang技術在行動物聯網開發中的作用 Golang技術在行動物聯網開發中的作用 May 09, 2024 pm 03:51 PM

Golang技術在行動物聯網開發中的作用

golang可變參數是否可以用於函數傳回值? golang可變參數是否可以用於函數傳回值? Apr 29, 2024 am 11:33 AM

golang可變參數是否可以用於函數傳回值?

See all articles