代码之家  ›  专栏  ›  技术社区  ›  Aaron Yodaiken

完成时向队列添加通道结果的更惯用方法

  •  2
  • Aaron Yodaiken  · 技术社区  · 15 年前

    queue.add(result) 在GORDOTIN的末尾,应该把东西添加到队列中。

    有没有办法更好地做到这一点呢?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Ross Light    15 年前

    你的问题实际上有两个部分:如何在GO中排队数据,以及如何在不阻塞的情况下使用信道。

    var (
        ch = make(chan int) // You can add an int parameter to this make call to create a buffered channel
    
        // Do not buffer these channels!
        gFinished = make(chan bool)
        processFinished = make(chan bool)
    )
    func f() {
        go g()
        for {
            // send values over ch here...
        }
        <-gFinished
        close(ch)
    }
    func g() {
        // create more expensive objects...
        gFinished <- true
    }
    func processObjects() {
        for val := range ch {
            // Process each val here
        }
        processFinished <- true
    }
    func main() {
        go processObjects()
        f()
        <-processFinished
    }
    

    make

    编辑: