我必须使用信号量实现与线程的矩阵乘法。问题是我不了解信号量是如何工作的,我的结果矩阵充满了零和程序挂起。你能解释一下我做错了吗?
这是我的代码:
class Program
{
private static Semaphore semaphore = new Semaphore(0, 1);
static void Main(string[] args)
{
int size;
int[,] a = null, b = null, c = null;
bool isNumeric;
do
{
Console.Write("Insert size: ");
isNumeric = int.TryParse(Console.ReadLine(), out size);
}
while (!isNumeric || size < 2);
Console.WriteLine();
SquareMatrix.Init(size, ref a);
SquareMatrix.Init(size, ref b);
SquareMatrix.Init(size, ref c);
SquareMatrix.Fill(a);
SquareMatrix.Fill(b);
Console.WriteLine("Matrix 1:\n");
SquareMatrix.Display(a);
Console.WriteLine("Matrix 2:\n");
SquareMatrix.Display(b);
Console.WriteLine();
DateTime start = DateTime.Now;
for (int i = 0; i < size; i++)
{
Thread thread = new Thread(() => Multiply(i, size, a, b, c));
thread.Name = i.ToString();
thread.Start();
}
DateTime stop = DateTime.Now;
Console.WriteLine("Result (" + (stop - start).TotalMilliseconds + " ms):\n");
SquareMatrix.Display(c);
Console.ReadLine();
}
public static void Multiply(int i, int size, int[,] a, int[,] b, int[,] c)
{
semaphore.WaitOne();
for (int j = 0; j < size; j++)
{
c[i, j] = 0;
for (int k = 0; k < size; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
semaphore.Release();
}
}
和SquareMatrix代码:
static class SquareMatrix
{
private static readonly Random random = new Random();
public static void Init(int size, ref int[,] array)
{
array = new int[size, size];
}
public static void Fill(int[,] array)
{
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
array[i, j] = random.Next(-10, 10);
}
}
}
public static void Display(int[,] array)
{
string result = "";
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
result += array[i, j] + " ";
result += "\n";
}
Console.Write(result + "\n");
}
}