thinkerou
thinkerou

Reputation: 1877

How should I write goroutine?

Now I have the following code:

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)
    }
}

And it can run right.

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

Upvotes: 1

Views: 193

Answers (1)

thinkerou
thinkerou

Reputation: 1877

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
    }
}

It can run right.

Upvotes: 1

Related Questions