我一直试图通过多线程创建几个二维数组。每个线程都会生成一个小的2-D数组。所有的二维将被合并,这就是我遇到问题的地方。我在"//!this is causing error"
方法的底部评论了SimulatingMethod
。请分享您的见解。谢谢。
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;
}
}
}
}
}
答案 0 :(得分:1)
您应该按如下方式指定属性:
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
整除时,您应该处理这种情况。