doucheng5705 2016-01-16 19:51
浏览 43

关闭通道链接的goroutine的一种优雅方法是什么?

I'm a Go learner. In order better to understand the care and feeding of channels and goroutines, I'm trying to build a Sieve of Eratosthenes as a set of goroutines connected into a pipeline by channels.

Here's what I have so far:

// esieve implements a Sieve of Eratosthenes
// as a series of channels connected together
// by goroutines
package main

import "fmt"

func sieve(mine int, inch chan int) {
    start := true                        // First-number switch
    ouch := make(chan int)               // Output channel for this instance
    fmt.Printf("%v
", mine)             // Print this instance's prime
    for next := <-inch; next > 0; next = <-inch {  // Read input channel
        fmt.Printf("%v <- %v
",mine,next)         // (Trace)
        if (next % mine) > 0 {                     // Divisible by my prime?
            if start {                   // No; is it the first number through? 
                go sieve(next, ouch)     // First number - create instance for it
                start = false            // First time done
            } else {                     // Not first time
                ouch <- next             // Pass it to the next instance
            }
        }
    }
}

func main() {
    lim := 30                     // Let's do up to 30
    fmt.Printf("%v
", 2)         // Treat 2 as a special case
    ouch := make(chan int)        // Create the first segment of the pipe
    go sieve(3, ouch)             // Create the instance for '3'
    for prime := 3; prime < lim; prime += 2 { // Generate 3, 5, ...
        fmt.Printf("Send %v
", prime)        // Trace
        ouch <- prime                         // Send it down the pipe
    }
}

And as far as it goes, it works nicely.

However, when I finish the main loop, main exits before all the numbers still in the pipeline of sieve instances have propagated down to the end.

What is the simplest, most elegant, or generally accepted way to make a main routine wait for a set of goroutines (about which it only 'knows' of the first one) to complete?

  • 写回答

2条回答 默认 最新

  • dongshuql24533 2016-01-16 21:26
    关注

    As for your title question, killing worker goroutines when you don't need them anymore: You could use the Done idiom. Reads from a closed channel yield the zero value.

    Make a new channel done. When reads from this channel succeed, the goroutines know they should quit. Close the channel in main when you have all the values you need.

    Check if you can read from a channel done, and exit by returning, or read from next when that's available. This partially replaces the assignment to next in you for loop:

    select {
    case <-done:
    return
    case next = <- inch:
    }
    

    Ranging over a channel also works, since closing that channel exits the loop.

    As for the reverse, your body question, waiting for a set of goroutines to finish:

    Use sync.WaitGroup.

    var wg sync.WaitGroup
    wg.Add(goroutineCount)
    

    And when each goroutine finishes:

    wg.Done()
    

    Or use defer:

    defer wg.Done()
    

    To wait for all of them to report as Done:

    wg.Wait()
    

    In your example, simply call wg.Add(1) when you start a new goroutine, before you call wg.Done() and return. As long as you only reach zero once, wg.Wait() works as expected, so wg.Add(1) before wg.Done.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看