#region Parallel_Loop
static void MultiplyMatricesParallel(int[,] matA, int[,] matB, int[,] result)
{
int matACols = matA.GetLength(1);
int matBCols = matB.GetLength(1);
int matARows = matA.GetLength(0);
int count = 0;
// A basic matrix multiplication.
// Parallelize the outer loop to partition the source array by rows.
Parallel.For(0, matARows, i =>
{
for (int j = 0; j < matBCols; j++)
{
int temp = 0;
int numThreads = (commonFeatures.resultMatrix.GetLength(0)* commonFeatures.resultMatrix.GetLength(1));
int toProcess = numThreads;
var resetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate (object state) {
rowColCall(matACols, temp, matA, matB, i, j);
if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();
}), null);
resetEvent.WaitOne();
}
}); // Parallel.For
}
#endregion
public static int rowCol(int matACols, int temp, int [,] matA, int [,] matB, int i, int j) {
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
return temp;
}
public static void rowColCall(int matACols, int temp, int[,] matA, int[,] matB, int i, int j) {
int a = rowCol(matACols, temp, matA, matB, i, j);
Console.WriteLine(i + "," + j + " = " + a);
Console.ReadLine();
}
您好,
我通过在行* col乘法上使用线程池(ThreadPool.QueueUserWorkItem。)对线程池使用和对c#进行矩阵乘法进行了新的研究。 当我用矩阵执行我的代码{1 2 3 4; 0 0 2 4}和{1 4,1 5,3 6,4,7}它将我作为输出返回:
0,0 = 28 1,0 = 22 线程0x179c已退出,代码为0(0x0)。 线程0x1fd4已退出,代码为0(0x0)。
因此它计算前两个线程并在无限循环中等待;我不知道为什么。