本文介绍了我应该如何编写goroutine?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有以下代码:

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io"
    "math"
    "strconv"
)

func Md5Str(str string) string {
    m := md5.New()
    io.WriteString(m, str)
    return hex.EncodeToString(m.Sum(nil))
}

func compute(size int) int {
    num := int(math.Floor(float64(size+256*1024-1)) / 256 / 1024)
    return num
}

func out(s string) string {
    return "Hello: " + s
}

func main() {
    num := compute(4194304)
    for i := 0; i < num; i++ {
        key := Md5Str("503969280ff8679135937ad7d23b06c5" + "_" + strconv.Itoa(i))
        res := out(key + "_" + strconv.Itoa(i))
        fmt.Println(res)
    }
}

它可以正确运行.

我想并发运行代码,因为如果 out 函数长时间运行,并且并发运行将节省时间.

I want to concurrency run the code, because if the out function run long time and the concurrency run will save time.

推荐答案

感谢@zerkms,我根据以身作则:工作池

Thanks @zerkms, I re-wrote the following code base on Go by Example: Worker Pools

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io"
    "math"
    "strconv"
)

func Md5Str(str string) string {
    m := md5.New()
    io.WriteString(m, str)
    return hex.EncodeToString(m.Sum(nil))
}

func compute(size int) int {
    num := int(math.Floor(float64(size+256*1024-1)) / 256 / 1024)
    return num
}

func out(s string, jobs <-chan int, results chan<- string) {
    for j := range jobs {
        fmt.Println("Hello: " + s + strconv.Itoa(j))
        results <- s
    }
}

func main() {
    num := compute(4194304)
    jobs := make(chan int, num)
    results := make(chan string, num)

    for i := 0; i < num; i++ {
        key := Md5Str("503969280ff8679135937ad7d23b06c5" + "_" + strconv.Itoa(i))
        go out(key+"_"+strconv.Itoa(i), jobs, results)
    }

    for j := 0; j < num; j++ {
        jobs <- j
    }
    close(jobs)

    for k := 0; k < num; k++ {
        <-results
    }
}

它可以正确运行.

这篇关于我应该如何编写goroutine?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:19