如何运行最大数量的goroutines [英] How to run the maximum number of goroutines

查看:289
本文介绍了如何运行最大数量的goroutines的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

func find(start int, end int){
    for i := start; i < end ; i++ {
        // Do something...
    }
}

func main() {
    // Do something...
    // For example, I know: len = 1500
    // and run max goroutine are 3
    // will be
    go find(0, 500)
    go find(500, 1000)
    go find(1000, 1500)
    // Do something...
}

那是我事先知道goroutine的最大线程数和"length"的长度的时候. 但是,如果我不知道goroutine可以运行多少个线程,以及"length"的长度.有什么办法可以将长度"分成相等的部分进行线程处理吗? 例如:length = 10,可以运行的最大goroutine为2,它将把长度分成2个线程(10/2,每个长度为5)以便能够同时处理.

That is when I know in advance the maximum threads of goroutines and the length of "length". But if I do not know how many threads can run at goroutine, and the length of "length". Is there any way to divide "length" into equal sections for thread processing? For example: length = 10, max goroutine that can run is 2 and it will split length into 2 threads (10/2, each length is 5) to be able to handle simultaneously.

推荐答案

最大化吞吐量是摆脱瓶颈.首先,找出浪费最多时间的地方.

Maximizing throughput is about getting rid of bottlenecks. First of all find where is most time is lost.

有时候运行太多的goroutine并不能使事情变快,但会使它们变慢,因为goroutine开始争夺资源.通常,最快的配置是以最有效的方式使用资源的配置:如果事情受到计算的限制,那么最好将正在运行的goroutine的数量设置为等于CPU内核的数量.但是,如果它受到IO的限制,则可以通过测量其性能来选择最佳数目.

Sometimes running too many goroutines doesn’t make things faster but makes them slower, because goroutines start to compete for resources. Usually the fastest configuration is one that uses resources in the most effective way: if things are limited by computation then it's best to set the number of running goroutines equal to the number of CPU cores. But if it is limited by IO then choose the optimal number by measuring its performance.

找出减慢程序速度的主要因素-然后使其变得更快.

Find the main thing that is slowing down your program - then make it faster.

这篇关于如何运行最大数量的goroutines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆