gpt4 book ai didi

go - 我应该如何编写goroutine?

转载 作者:IT王子 更新时间:2023-10-29 02:12:13 26 4
gpt4 key购买 nike

现在我有以下代码:

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

最佳答案

感谢@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
}
}

它可以正常运行。

关于go - 我应该如何编写goroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com