douyou1901 2019-03-21 19:52
浏览 46
已采纳

运行恒定数量的goroutine

I'm not completely sure what's going on here so it's hard to generalize my question, but I'm going to try my very best.

In a video from a few years ago Matt Parker dared his viewers to find a power of two, which does not contain any digits which are a power of two. (For example, 2^16 = 65536. None of these digits individually are a power of two). Recently I got into learning Go and I thought it would be a nice introductory exercise to get used to the language.

I created this pretty quickly and then I decided to try to make it concurrent to make full use of my quad core processor. This is where things went downhill.

The goal here is to run a constant amount of goroutines each of which processes a different batch of numbers. I implemented the program like so:

package main

import (
    "log"
    "math/big"
    "runtime"
)

//The maximum amount of goroutines
const routineAmt int = 3

//The amount of numbers for each routine to check
const rangeSize int64 = 5000

//The current start of the range to start checking
var rangeIndex int64 = 0

func main() {
    //loop forever
    for {
        //if we have less routines running than the maximum
        if runtime.NumGoroutine() < routineAmt {
            c := make(chan bool)
            // start a new one to check the next range:
            go checkRange(rangeIndex, rangeIndex+rangeSize, c)
            // wait for the signal that the values have been copied to the function, so that we can increment them safely:
            <-c
            close(c)
            // increment the rangeIndex for the next routine which will start:
            rangeIndex += rangeSize
        }
    }
}

// Function to check a range of powers of two, whether they contain any power-of-two-digits
func checkRange(from, to int64, c chan bool) {
    c <- true // signal to the main routine that the parameter values have been copied

    // Loop through the range for powers of two, which do not contain any power-of-two-digits
    for i := from; i < to; i++ {
        num := big.NewInt(2)
        num.Exp(num, big.NewInt(i), nil)
        if !hasStringPowerOfTwo(num.String()) {
            log.Println("Found 2 ^", i)
        }
    }
    log.Printf("Checked range %d-%d
", from, to)
}

// Function to check if a string contains any number which is a power of two
func hasStringPowerOfTwo(input string) bool {
    powersOfTwo := [4]rune{'1', '2', '4', '8'}
    for _, char := range input {
        if runeInArray(char, powersOfTwo) {
            return true
        }
    }
    return false
}

// Function to check if a list of runes contains a certain rune
func runeInArray(a rune, list [4]rune) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

After waiting about 15 minutes or so, the program still did not finish a single go routine (that is, I did not see log.Printf("Checked range %d-%d ", from, to) in the console)

I tried lowering the range size to 5, which resulted in a few goroutines to be completed but it abruptly stopped at the range 2840-2845. I thought this might be due to the numbers getting bigger and the calculation taking more time, but this doesn't make sense as the stop is very abrupt. If this were the case I would expect the slowdown to be at least a little gradual.

  • 写回答

1条回答 默认 最新

  • duanmianzhou5353 2019-03-22 02:54
    关注

    You should not be using a for loop with a check on runtime.NumGoroutine to make sure you don't have too many routines running, because the loop will prevent the goruntime to schedule your routines properly, it will slowdown the whole thing.

    Instead, you should use a buffered channel which signals when a routine is done, so that you can start a new one.

    I have adjusted your main function and checkRange function:

    func main() {
            var done = make(chan struct{}, routineAmt)
            //loop forever
            for i := 0; i < routineAmt; i++ {
                    // start a new one to check the next range:
                    go checkRange(done, rangeIndex, rangeIndex+rangeSize)
                    // increment the rangeIndex for the next routine which will start:
                    rangeIndex += rangeSize
            }
    
            for range done {
                    // start a new one to check the next range:
                    go checkRange(done, rangeIndex, rangeIndex+rangeSize)
                    // increment the rangeIndex for the next routine which will start:
                    rangeIndex += rangeSize
            }
    }
    
    // Function to check a range of powers of two, whether they contain any power-of-two-digits
    func checkRange(done chan<- struct{}, from, to int64) {
            // Loop through the range for powers of two, which do not contain any power-of-two-digits
            for i := from; i < to; i++ {
                    num := big.NewInt(2)
                    num.Exp(num, big.NewInt(i), nil)
                    if !hasStringPowerOfTwo(num.String()) {
                            log.Println("Found 2 ^", i)
                    }
            }
            log.Printf("Checked range %d-%d
    ", from, to)
    
            // let our main go routine know we're done with this one
            done <- struct{}{}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况