感谢大家帮助我解决这个问题。但是,尽管您都帮助我理解了该技术,但我认为没有人真正提供既可行又简单/易于理解的功能。
最后,我认为作为对我的特定问题的解答,我认为它更易于理解和实用,因此,如果其他人有相同的问题,我将在此处发布。
不知何故,最终看起来很像OneOfOne发布的内容,这很棒,因为现在我明白了。但是我一开始发现OneOfOne的代码很难理解,因为将函数传递给函数使人们很难理解到底是什么。我认为这种方式更有意义:
package mainimport ("fmt""sync")const xthreads = 5 // Total number of threads to use, excluding the main() threadfunc doSomething(a int) { fmt.Println("My job is",a) return}func main() { var ch = make(chan int, 50) // This number 50 can be anything as long as it's larger than xthreads var wg sync.WaitGroup // This starts xthreads number of goroutines that wait for something to do wg.Add(xthreads) for i:=0; i<xthreads; i++ { go func() { for { a, ok := <-ch if !ok { // if there is nothing to do and the channel has been closed then end the goroutine wg.Done() return } doSomething(a) // do the thing } }() } // Now the jobs can be added to the channel, which is used as a queue for i:=0; i<50; i++ { ch <- i // add i to the queue } close(ch) // This tells the goroutines there's nothing else to do wg.Wait() // Wait for the threads to finish}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)