我怎样才能产生依赖于前辈的例行程序?

时间:2015-12-16 23:17:20

标签: go concurrency goroutine

比如说我想填充这个矩阵:

| 0 | 0 | 0 | 0 |
| 0 | 1 | 2 | 3 |
| 0 | 2 | 3 | 4 |
| 0 | 3 | 4 | 5 |

具体来说,我想填充它,以便每个单元格遵循规则,

formula

在英语中,单元格的值大于其toplefttopleft邻居的最大值。值。

因为每个单元格只有三个依赖项(toplefttopleft个邻居),所以我可以在m[1][1]填充单元格({{1} }),一旦填充了这些,我可以填充标记为1的单元格,因为它们的所有依赖项都已填充。

2

如何旋转1个常规,然后2个,然后3个,然后4个...,填充该矩阵的每个对角线?也许更具体地说,我怎样才能在开始依赖单元格之前等待邻居完成?

[编辑] :感谢评论,@ Zippoxer!为了澄清,我问Go中的语法是什么,以运行一个依赖于另一个完成的go例程。因为只有一个go-routine结束时可以启动多个新的例程,所以它不像没有并发性地调用事物那么简单!

2 个答案:

答案 0 :(得分:2)

希望这是一个人为的例子,因为这绝对不是最快的解决方案,但也许它就是你想要的。

每个单元格都在自己的goroutine中运行,并且有自己的通道,大致代表它的依赖关系。一个单元知道它的依赖关系一旦从其通道读取三个值就已经解决了。当一个单元格完成时,它会将一些值传递给它所有依赖的通道。

import "sync"

type empty struct{}

func contrivedMathThing(i, j int) ([][]int) {

    var wg sync.WaitGroup
    wg.Add(i * j)

    // Make two-dimensional slices for the channels that the goroutines will
    // wait on, and for the results of each cell. Two dimensional slices are
    // more annoying to make, but I think make the example a bit more clear.
    chans := make([][]chan empty, i)
    results := make([][]int, i)
    for a := 0; a < i; a++ {
        chans[a] = make([]chan empty, j)
        results[a] = make([]int, j)
        for b := 0; b < j; b++ {
            chans[a][b] = make(chan empty, 3)
        }
    }

    for a := 0; a < i; a++ {
        for b := 0; b < j; b++ {
            go func(a, b int, waitc <-chan empty) {
                defer wg.Done()

                // Wait for all dependencies to complete
                <-waitc
                <-waitc
                <-waitc

                // Compute the result
                // Too lazy to write...

                // Save the result to the results array
                results[a][b] = result

                // Signal all dependents that one of their dependencies has
                // resolved
                if a < i - 1 {
                    chans[a + 1][b] <- empty{} 
                }
                if b < j - 1 {
                    chans[a][b + 1] <- empty{}
                }
                if a < i - 1 && b < j - 1 {
                    chans[a + 1][b + 1] <- empty{}
                }

            }(a, b, chans[a][b])
        }
    }

    // All cells in the first row and first column need to start out with two
    // of their dependencies satisfied.
    for a := 1; a < i; a++ {
        chans[a][0] <- empty{}
        chans[a][0] <- empty{}
    }
    for b := 1; b < j; b++ {
        chans[0][b] <- empty{}
        chans[0][b] <- empty{}
    }

    // Unblock the cell at [0][0] so this show can get started
    close(chans[0][0])

    wg.Wait()

    return results
}

答案 1 :(得分:1)

使用channels

goroutine正在等待另一个goroutine:

done := make(chan bool)

go func() {
  // Work...
  done <- true // Signal we're done.
}()

go func() {
  <- done // Wait for the previous goroutine to signal.
  // Work...
}()