gpt4 book ai didi

C# 线程在第二个线程上崩溃,不确定如何修复

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:34 25 4
gpt4 key购买 nike

为了好玩,我创建了一个 mandelbrot 程序。我现在正试图通过将图像分成两个左/右部分由两个线程处理来使其多线程化。但是,应用程序一启动就崩溃(虽然根据我的控制台输出,第一个线程在崩溃后继续,但第二个线程永远不会启动),我不确定该怎么做。

崩溃发生在行 this.output[x][y] = this.calculate_pixel_rgb(x, y); 并说我缺少一个对象引用,我没有理解,因为它适用于第一个线程。

    public void compute_all()
{
this.setcolors(); this.zoom_multiplier = (4 / this.zoom / this.resolution);
Thread thread1 = new Thread(new ParameterizedThreadStart(computation_thread)); thread1.Start(new double[] { 0, 0.5 });
Thread thread2 = new Thread(new ParameterizedThreadStart(computation_thread)); thread2.Start(new double[] { 0.5, 1 });
thread1.Join(); thread2.Join();
}

public void computation_thread(object threadinfo)
{
double[] parameters = (double[])threadinfo;

this.output = new int[this.resolution][][];
for (int x = (int)(this.resolution * parameters[0]); x < (int)(this.resolution * parameters[1]); x++)
{
this.output[x] = new int[this.resolution][];
for (int y = 0; y < this.resolution; y++)
{
this.output[x][y] = this.calculate_pixel_rgb(x, y);
this.pixels_completed++;
}
}
}

最佳答案

您的两个线程正在操作同一个输出缓冲区,相互覆盖。如果可以避免,不要在线程之间共享内存;它引起的只是悲伤。

如果本练习的目的是学习如何操作原始线程,那么退后一步,研究为什么跨两个线程共享内存不是一个好主意。

如果本练习的目的是并行化分形计算,那么请忘记操作原始线程。学习如何使用任务并行库会做得更好。

线程在逻辑上是 worker ,谁愿意管理一堆 worker ? TPL 鼓励您将并行化视为对可以并行完成的任务 的操作。让 TPL 负责计算分配给您的任务的 worker 数。

关于C# 线程在第二个线程上崩溃,不确定如何修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078593/

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