Go中的多线程无限循环



为了帮助扩展我的Go知识,我决定为Collatz猜想编写一个迭代器。有了它的工作,我现在想使它多线程。我可以找到多线程一个for循环的各种例子,但它们似乎是基于线程之间的每次迭代定义的界限。例:for n := range(10) {;在我的用例中,N的上界是未知的(取决于代码运行的时间)。完整的代码可以在Github上看到,但是,总结:

n := 0
for {
stepsToResolve = resolveN(n) //<- "Multithread this"
n++
}

您的示例缺少退出条件,因此有点奇怪。也就是说,你并不总是提前知道你要启动多少子程序。一个典型的处理方法是使用sync.WaitGroup。例如:

for {
wg.Add(1) // declare new goroutine
go func(i int, wg *sync.WaitGroup) {
defer wg.Done() // when work is done, declare termination
log.Printf("hello wait group %vn", i)
}(i, &wg)
// Please add a stop condition !
}
wg.Wait() // prevent your main program to return until all goroutines have ended

但是在您的情况下,创建数千个例程似乎没有帮助(您可能有更少的可用cpu)。在这种情况下,您可以使用具有有限并发性的池。如果你想使用它,我为它写了一个库:

import "github.com/aherve/gopool"
func main() {
pool := gopool.NewPool(8) // creates pool with limited concurrency of 8
for {
pool.Add(1)
go func(i int, pool *gopool.GoPool) {
defer pool.Done()
time.Sleep(time.Second)
log.Printf("hello pool %vn", i)
}(i, pool)
// Please add a stop condition !
}
pool.Wait()
}

在这个版本中,同时启动的例程不超过8个,代码与waitGroup的使用非常相似。

最新更新