利用 goroutines 和通道实现自上而下的树构建功能

Utilizing goroutines and channels for top-to-bottom tree building function

我是 golang 和 channels/goroutines 的新手,但我了解概念和简单用法。

现在我正在尝试实现并发树构建功能,算法非常简单 - 从上到下 我为每个节点添加 2 个子节点,然后为每个子节点执行相同的操作 depthLimit。这是非并发代码:

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type Node struct {
    Name     string
    Children []Node
}

func main() {
    mainNode := Node{"p", nil}
    AddChildrenToNode(&mainNode, 4, 0)

    b, _ := json.MarshalIndent(mainNode, "", "  ")
    fmt.Println(string(b)) // print as json
}

func AddChildrenToNode(node *Node, depthLimit int, curDepth int) {
    curDepth++
    if curDepth >= depthLimit {
        return // reached depth limit
    }

    time.Sleep(500 * time.Millisecond) // imitating hard work c:
    fmt.Print(".")                     // status indicator
    // add children
    node.Children = []Node{
        Node{node.Name + "-l", nil},
        Node{node.Name + "-r", nil},
    }
    for idx, _ := range node.Children {
        AddChildrenToNode(&node.Children[idx], depthLimit, curDepth) // run this for every created child, recursively
    }
}

但是现在我在为 goroutine 使用重写它时遇到了困难。问题是我们实际上无法知道 'building' 何时完成并向 block/unblock main 发出信号。我错过了什么吗?我也试着玩 sync.WaitingGroup.

您可以将 goroutine 引入此算法的一种方法是使用单独的 goroutine 来添加子节点,假设您无法在完成 "hard work" 部分之前真正添加这些子节点。

func AddChildrenToNode(node *Node, wg *sync.WaitGroup,depthLimit int, curDepth int) {
  // work
  go func() {
    defer wg.Done()
    node.Children = []Node{
        Node{node.Name + "-l", nil},
        Node{node.Name + "-r", nil},
    }
    for idx, _ := range node.Children {
        AddChildrenToNode(&node.Children[idx], depthLimit, curDepth) // run this for every created child, recursively
    }
  }()
}

使用此方案,您最终会创建 2^(depth-1)-1 个 goroutine,因此您可以在 main 中等待它们完成:

func main() {
 ...
  wg:=sync.WaitGroup{}
  wg.Add((1<<(depth-1))-1)
  AddChildrenToNode(&mainNode, 4, 0)
  wg.Wait()
  ...

还有其他方法可以做到这一点,比如为左右节点添加一个 goroutine。

我想我终于想出了如何实现它。 @burak-serdar的回答帮了大忙。实际上,与其将整个 AddChildrenToNode 推送到 goroutine 池,我们还可以添加到我们的等待组,然后使用 lambda 仅 运行 goroutine 中的下一层。而且因为我们在这一层之前添加到我们的等待组 - 它保证不会溢出 'dones' 值所以我们总是会在填充所有 children 时退出。这是代码:

package main

import (
    "encoding/json"
    "fmt"
    "math/rand"
    "sync"
    "time"
)

type Node struct {
    Name     string
    Children []Node
}

func main() {
    rand.Seed(time.Now().UnixNano())

    mainNode := Node{"p", nil}
    var wg sync.WaitGroup

    AddChildrenToNode(&mainNode, 4, 0, &wg)
    wg.Wait()

    b, _ := json.MarshalIndent(mainNode, "", "  ")
    fmt.Println(string(b)) // print as json
}

func AddChildrenToNode(node *Node, depthLimit int, curDepth int, wg *sync.WaitGroup) {
    curDepth++
    if curDepth >= depthLimit {
        return // reached depth limit
    }

    // Dynamic children count
    cN := rand.Intn(5)
    for i := 0; i <= cN; i++ {
        node.Children = append(node.Children, Node{node.Name + "-l", nil})
    }

    //node.Children = []Node{}

    time.Sleep(500 * time.Millisecond) // imitating hard work c:

    for idx, _ := range node.Children {
        fmt.Println(".")
        wg.Add(1) // it will always lag behind the next done so the flow wont be broken
        go func(idx int) {
            AddChildrenToNode(&node.Children[idx], depthLimit, curDepth, wg) // run this for every created child, recursively
            wg.Done()
        }(idx)
    }
}