为了账号安全,请及时绑定邮箱和手机立即绑定

Julia 设置图像渲染被并发毁了

Julia 设置图像渲染被并发毁了

Go
POPMUISE 2022-01-04 10:47:30
我有以下代码要更改为并发程序。// Stefan Nilsson 2013-02-27// This program creates pictures of Julia sets (en.wikipedia.org/wiki/Julia_set).package mainimport (    "image"    "image/color"    "image/png"    "log"    "math/cmplx"    "os"    "strconv")type ComplexFunc func(complex128) complex128var Funcs []ComplexFunc = []ComplexFunc{    func(z complex128) complex128 { return z*z - 0.61803398875 },    func(z complex128) complex128 { return z*z + complex(0, 1) },}func main() {    for n, fn := range Funcs {        err := CreatePng("picture-"+strconv.Itoa(n)+".png", fn, 1024)        if err != nil {            log.Fatal(err)        }    }}// CreatePng creates a PNG picture file with a Julia image of size n x n.func CreatePng(filename string, f ComplexFunc, n int) (err error) {    file, err := os.Create(filename)    if err != nil {        return    }    defer file.Close()    err = png.Encode(file, Julia(f, n))    return}// Julia returns an image of size n x n of the Julia set for f.func Julia(f ComplexFunc, n int) image.Image {    bounds := image.Rect(-n/2, -n/2, n/2, n/2)    img := image.NewRGBA(bounds)    s := float64(n / 4)    for i := bounds.Min.X; i < bounds.Max.X; i++ {        for j := bounds.Min.Y; j < bounds.Max.Y; j++ {            n := Iterate(f, complex(float64(i)/s, float64(j)/s), 256)            r := uint8(0)            g := uint8(0)            b := uint8(n % 32 * 8)            img.Set(i, j, color.RGBA{r, g, b, 255})        }    }    return img}// Iterate sets z_0 = z, and repeatedly computes z_n = f(z_{n-1}), n ≥ 1,// until |z_n| > 2  or n = max and returns this n.func Iterate(f ComplexFunc, z complex128, max int) (n int) {    for ; n < max; n++ {        if real(z)*real(z)+imag(z)*imag(z) > 4 {            break        }        z = f(z)    }    return}这种变化会导致图像看起来非常不同。图案基本相同,但有很多以前没有的白色像素。这里发生了什么?
查看完整描述

1 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

有2个问题:

  1. 你实际上并没有等待你的 goroutines 完成。

  2. 您不会传递i and j给 goroutine,因此它们几乎总是最后一个 i 和 j。

您的函数应该类似于:

func Julia(f ComplexFunc, n int) image.Image {

    var wg sync.WaitGroup

    bounds := image.Rect(-n/2, -n/2, n/2, n/2)

    img := image.NewRGBA(bounds)

    s := float64(n / 4)

    for i := bounds.Min.X; i < bounds.Max.X; i++ {

        for j := bounds.Min.Y; j < bounds.Max.Y; j++ {

            wg.Add(1)

            go func(i, j int) {

                n := Iterate(f, complex(float64(i)/s, float64(j)/s), 256)

                r := uint8(0)

                g := uint8(0)

                b := uint8(n % 32 * 8)

                img.Set(i, j, color.RGBA{r, g, b, 255})

                wg.Done()

            }(i, j)

        }

    }

    wg.Wait()

    return img

}

奖金提示,当潜入并发性,它通常是一个好主意,尝试用你的代码的比赛探测器。


您可能必须使用互斥锁进行调用,img.Set但我不太确定,也无法测试 atm。


查看完整回答
反对 回复 2022-01-04
  • 1 回答
  • 0 关注
  • 214 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号