我该怎么写goroutine?

时间:2017-03-28 00:52:16

标签: go

现在我有以下代码:

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函数运行很长时间并且并发运行会节省时间。

1 个答案:

答案 0 :(得分:1)

感谢@zerkms,我在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
    }
}

它可以正常运行。