Многопоточность - C# (204876)
Формулировка задачи:
Доброго времени суток всем. Народ задача стоит многопоточное умножение матриц. Ну если я правильно всё догнал, то получается примерно такое. Но работает как то не совсем правильно. Где ошибся?(первое многопоточное приложение, сразу не убивать).
static void Mult() { Thread thread; Matr3= new int[n, n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { _i = i; _j = j; thread = new Thread(Value); thread.Start(); } } } static void Value() { int i = _i; int j = _j; Matr[i,j] = 0; for (int k = 0; k < n; k++) { Matr3[i, j] += Matr1[i, k] * Matr2[k, j]; } }
Решение задачи: «Многопоточность»
textual
Листинг программы
using System; using System.Threading.Tasks; namespace ConsoleApplication8 { class Matrix { public static int[,] Multiply(int[,] a, int[,] b) { if (a.GetLength(1) != b.GetLength(0)) throw new ArgumentException(); var result = new int[a.GetLength(0), b.GetLength(1)]; Parallel.For(0, a.GetLength(0), i => Parallel.For(0, b.GetLength(1), j => result[i, j] = MultiplyR(a, b, i, j))); return result; } private static int MultiplyR(int[,] a, int[,] b, int i, int j) { int result = 0; for (int k = 0; k < a.GetLength(1); k++) result += a[i, k]*b[k, j]; return result; } } class Program { private static int[,] a = {{2, 1}, {2, 1}}; private static int[,] b = {{2, 1, 3}, {2, 1, 3}}; static void Main() { var res = Matrix.Multiply(a, b); for (int i = 0; i < res.GetLength(0); i++) { for (int j = 0; j < res.GetLength(1); j++) Console.Write(res[i, j] + " "); Console.WriteLine(); } Console.ReadKey(); } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д