下面是计算 C(36,8) 并将结果保存到文件的代码


func combine_dfs(n int, k int) (ans [][]int) {

    temp := []int{}

    var dfs func(int)

    dfs = func(cur int) {

        if len(temp)+(n-cur+1) < k {

            return

        }

        if len(temp) == k {

            comb := make([]int, k)

            copy(comb, temp)

            ans = append(ans, comb)

            return

        }

        temp = append(temp, cur)

        dfs(cur + 1)

        temp = temp[:len(temp)-1]

        dfs(cur + 1)

    }

    dfs(1)

    return

}


func DoCombin() {

    fmt.Printf("%v\n", "calculator...")

    cst := []byte{}

    for i := 'a'; i <= 'z'; i++ {

        cst = append(cst, byte(i))

    }

    for i := '0'; i <= '9'; i++ {

        cst = append(cst, byte(i))

    }

    n := 36

    k := 8

    arr := combine_dfs(n, k)

    fmt.Printf("%v\n", "writefile...")

    file, _ := os.OpenFile("result.txt", os.O_CREATE|os.O_TRUNC|os.O_RDWR|os.O_APPEND, 0666)

    defer file.Close()

    for _, m := range arr {

        b:= bytes.Buffer{}

        b.Reset()

        for _, i := range m {

            b.WriteByte(cst[i-1])

        }

        b.WriteByte('\n')

        file.Write(b.Bytes())

    }

}

但是我写文件太慢了..


所以我想使用 goroutine 来写文件(使用 pool 来限制 goroutine 的数量):


func DoCombin2() {

    fmt.Printf("%v\n", "calculator...")

    cst := []byte{}

    for i := 'a'; i <= 'z'; i++ {

        cst = append(cst, byte(i))

    }

    for i := '0'; i <= '9'; i++ {

        cst = append(cst, byte(i))

    }

    n := 36

    k := 8

    arr := combine_dfs(n, k)

    fmt.Printf("%v\n", "writefile...")

    file, _ := os.OpenFile("result.txt", os.O_CREATE|os.O_TRUNC|os.O_RDWR|os.O_APPEND, 0666)

    defer file.Close()

    pool := make(chan int, 100)

    for _, m := range arr {

        go func(m []int) {

            pool <- 1

            b := bytes.Buffer{}

            b.Reset()

            for _, i := range m {

                b.WriteByte(cst[i-1])

            }

        }(m)

    }

}


有什么办法可以避免内存爆炸?

  • 1.为什么使用了sync.Pool后还是无法避免?

  • 2.有什么方法可以限制 Windows 中的内存使用(我知道在 Linux 中)?

  • 3.还有其他方法可以避免内存爆炸吗?

  • 4.内存爆炸是因为bytes.Buffer吗?如何手动释放 bytes.Buffer?