Shutdown “worker” go routine after buffer is empty

后端 未结 3 394
夕颜
夕颜 2021-01-15 08:19

I want my go routine worker (ProcessToDo() in the code below) to wait until all \"queued\" work is processed before shutting down.

The worker routine

3条回答
  •  孤城傲影
    2021-01-15 08:40

    It's usually a bad idea to have a consumer of a channel close it, since sending on a closed channel is a panic.

    In this case, if you never want to interrupt the consumer before all messages have been sent, just use a for...range loop and close the channel when you're done. You will also need a signal like a WaitGroup to wait for the goroutine to finish (rather than using time.Sleep)

    http://play.golang.org/p/r97vRPsxEb

    var wg sync.WaitGroup
    
    func ProcessToDo(todo chan string) {
        defer wg.Done()
        for work := range todo {
            fmt.Printf("todo: %q\n", work)
            time.Sleep(100 * time.Millisecond)
    
        }
        fmt.Printf("Shutting down ProcessToDo - todo channel closed!\n")
    
    }
    
    func main() {
        todo := make(chan string, 100)
        wg.Add(1)
        go ProcessToDo(todo)
    
        for i := 0; i < 20; i++ {
            todo <- fmt.Sprintf("Message %02d", i)
        }
    
        fmt.Println("*** all messages queued ***")
        close(todo)
        wg.Wait()
    }
    

提交回复
热议问题