组合通过多个线程创建的数组
本文关键字:创建 数组 线程 组合 | 更新日期: 2023-09-27 17:58:30
我一直在尝试通过多线程创建两个2-D数组。每个线程将生成一个小的二维数组。所有的二维图都将被合并,这就是我的问题所在。我在SimulatingMethod
方法的底部评论了"//!this is causing error"
。请分享您的见解。非常感谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadExample
{
class Program
{
static void Main(string[] args)
{
double[,] randSims;
randSims = SimulatingClass.SimulatingMethod();
}
}
class SimulatingClass
{
public static double[,] SimulatingMethod()
{
int rowCount = 9;
int columnCount = 1;
int NumberOfCores = System.Environment.ProcessorCount;
int RowsForEachThread = rowCount / NumberOfCores;
Thread[] arrayOfThread = new Thread[NumberOfCores];
DataStuff[] dataStuff= new DataStuff[NumberOfCores];
for (int i = 0; i < NumberOfCores; i++)
{
dataStuff[i] = new DataStuff(RowsForEachThread, columnCount);
arrayOfThread[i] = new Thread(new ThreadStart(dataStuff[i].UpdateMatrixData));
arrayOfThread[i].Name = "Thread" + i;
arrayOfThread[i].Start();
}
for (int i = 0; i < NumberOfCores; i++)
{
arrayOfThread[i].Join();
}
//start combining arrays from different threads
var list = new List<double[,]>();
for (int m = 0; m < NumberOfCores; m++)
{
list.AddRange(dataStuff[m]); //!this is causing error
}
//trying to convert list back to array
double[,] array3 = list.ToArray(); //!this is causing error
return array3;
}
}
class DataStuff
{
public double G;
public double[,] M;
public long steps, trials;
public DataStuff(long _steps, long _trials)
{
M = new Double[_steps, _trials]; // <- M is created in the constructor
G = 60;
steps = _steps;
trials = _trials;
}
public void UpdateMatrixData()
{
for (int i = 0; i < steps; i++)
{
for (int j = 0; j < trials; j++)
{
M[i, j] = i + j;
}
}
}
}
}
您应该指定如下属性:
list.Add(dataStuff[m].M);
这是因为dataStuff[m]
的类型是DataStuff
,但类型double[,]
应作为列表项。
如果我理解正确的话,你需要一个整合的2D阵列。试着用想要的尺寸来声明它:
double[,] array3 = new double[rowCount, columnCount];
并在处理后将数据从dataStuff
阵列复制到它:
for (int m = 0; m < NumberOfCores; m++)
{
Array.Copy(dataStuff[m].M, 0, array3, m * columnCount * RowsForEachThread, dataStuff[m].M.Length);
}
return array3;
而且您根本不需要list
。
请注意,您有可能的与舍入有关的问题:
int RowsForEachThread = rowCount / NumberOfCores;
当rowCount
不能被NumberOfCores
整除时,您应该处理这种情况。