亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

在golang中并行遞歸掃描樹

在golang中并行遞歸掃描樹

Go
慕萊塢森 2022-01-17 18:37:03
我有一棵二叉樹,它訪問節點的速度相對較快,但葉子除外——它們可能慢 100-1000 倍。我有一個遞歸算法,我想在 go 中實現(我是新手)。因為我必須到達葉子節點才能從并行性中受益,所以我需要在樹中將執行并行化得更高。不過,這可能會導致數百萬個 goroutines。用信號量限制這一點似乎不是“可行”的方式——沒有這樣的同步原語。我擔心的另一個問題是,實際上,一個頻道有多貴,我是否應該使用等待組。我的樹是抽象的,算法在它上面運行,按級別和索引識別項目。// l3               0//               /    \// l2          0        1//           /  \     /   \// l1       0    1   2     3//         / \  / \ / \   / \// l0     0  1 2  3 4 5  6  7例如,我可以使用這樣的函數來計算向量中所有項目的總和:func Sum(level, index int, items []int) int {    if level == 0 {return items[index]}    return Sum(level-1, index*2, items) + Sum(level-1, index*2+1, items)}我的方法應該是什么?有人可以指出我在 Go 中實現的遞歸樹多線程算法嗎?
查看完整描述

2 回答

?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

聽起來你需要一個工作池。這是我剛剛寫的一個例子:https: //play.golang.org/p/NRM0yyQi8X


package main


import (

    "fmt"

    "sync"

    "time"

)


type Leaf struct {

    // Whatever

}


func worker(i int, wg *sync.WaitGroup, in <-chan Leaf) {

    for leaf := range in {

        time.Sleep(time.Millisecond * 500)

        fmt.Printf("worker %d finished work: %#v\n", i, leaf)

    }

    fmt.Printf("worker %d exiting\n", i)

    wg.Done()

}


func main() {

    var jobQueue = make(chan Leaf)

    var numWorkers = 10

    // the waitgroup will allow us to wait for all the goroutines to finish at the end

    var wg = new(sync.WaitGroup)

    for i := 0; i < numWorkers; i++ {

        wg.Add(1)

        go worker(i, wg, jobQueue)

    }


    // enqueue work (this goes inside your tree traversal.)

    for i := 0; i < 100; i++ {

        jobQueue <- Leaf{}

    }


    // closing jobQueue will cause all goroutines to exit the loop on the channel.

    close(jobQueue)

    // Wait for all the goroutines to finish

    wg.Wait()

}


查看完整回答
反對 回復 2022-01-17
?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

我強烈建議從上到下閱讀這篇優秀的博客文章:

https://blog.golang.org/pipelines

它不僅涵蓋了您所需要的示例(即并行文件樹遍歷計算 MD5 文件校驗和),還涵蓋更多內容:

  • 扇入/扇出通道技術

  • 并行性

  • 通過完成通道取消管道

  • 通過錯誤通道進行流水線錯誤鏈接

  • 有界并行

最后一個主題,有界并行,用于確?!靶凶摺钡拇蠊濣c目錄樹不會創建過多的 go-routines:bounded.go


查看完整回答
反對 回復 2022-01-17
  • 2 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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