Using a channel for dispatching tasks to go routine

江枫思渺然 提交于 2019-12-13 03:56:36

问题


I am writing a program to render diagrams. Todo so I'm searching for all files and want to dispatch them async to go routines to process them in parallel. But I think I misunderstood the concept of channels.

files := umlFiles("uml") // list of strings

queue := make(chan string)
for i := 0; i < 4; i++ {
    go func(queue chan string) {
        file, ok := <-queue
        if !ok {
            return
        }

        exec.Command("some command", file).Run()
    }(queue)
}
for _, f := range files {
    queue <- f
}
close(queue)

This will run in a deadlock after it is done with the first 4 files but never continues with the rest of the files.

Can i use a channel to dispatch tasks to running go routines and stop them when all of the tasks are done? If so what is wrong with the code above?

Used to get here:
how-to-stop-a-goroutine
go-routine-deadlock-with-single-channel


回答1:


You are very close. The problem you have is you are launching 4 goroutines which all do 1 piece of work, then return. Try this instead

for i := 0; i < 4; i++ {
    go func(queue chan string) {
        for file := range queue {
            exec.Command("some command", file).Run()
        }
    }(queue)
}

Once queue is closed these will return.



来源:https://stackoverflow.com/questions/48734453/using-a-channel-for-dispatching-tasks-to-go-routine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!