dongmimeng5500 2018-02-26 11:01
浏览 25
已采纳

做完前去例行检查

I'm tying to execute things async with multiple go routines. I pass in the number of "threads" to use to process the files async. The files is an array of Strings to process.

queue := make(chan string)

threadCount := c.Int("threads")

if c.Int("threads") < len(files) {
    threadCount = len(files)
} 

log.Infof("Starting %i processes", c.Int("threads"))

for i := 0; i < threadCount; i++ {
    go renderGoRoutine(queue)
}

for _, f := range files {
    queue <- f
}
close(queue)

And the routine itself looks like this:

func renderGoRoutine(queue chan string) {
    for file := range queue { 
        // do some heavy lifting stuff with the file
    }
}

This does work fine whenever i use just one thread. As soon as i take more then one it does exit/leave the scope before it is done with all the go routines.

How do I make it process everything?

Previous question: Using a channel for dispatching tasks to go routine

  • 写回答

3条回答 默认 最新

  • duanfang2708 2018-02-26 11:19
    关注

    You are using the channel to publish work to be done. As soon as the last item is taken from the queue (not finished processing), your program exits.

    You could use a channel to write to at the end of renderGoRoutine to signal the end of processing.

    At the top:

    sync := make(chan bool)
    

    In renderGoRoutine at the end (Assuming it is in the same file):

    sync <- true
    

    At the bottom:

    for f := range sync {
        <- sync
    }
    

    Now your program waits until the number of files are processed.

    Or to have a complete example:

    queue := make(chan string)
    sync := make(chan bool)
    
    threadCount := c.Int("threads")
    
    if c.Int("threads") < len(files) {
        threadCount = len(files)
    } 
    
    log.Infof("Starting %i processes", c.Int("threads"))
    
    for i := 0; i < threadCount; i++ {
        go renderGoRoutine(queue)
    }
    
    for _, f := range files {
        queue <- f
    }
    close(queue)
    
    for f := range sync {
        <- sync
    }
    

    And the routine should be changed like this:

    func renderGoRoutine(queue chan string) {
        for file := range queue { 
            // do some heavy lifting stuff with the file
            sync <- true
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站