#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();
}
你好,
我是线程池使用的新手,并通过在 row*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) 退出。
所以它计算前两个线程并无限循环等待;我不知道为什么。