Вычислить скалярное произведение векторов методом parallel.for - C#
Формулировка задачи:
Вычислить скалярное произведение векторов методом parallel.for правильно? если нет помогите(
using System;
using System.Threading.Tasks;
namespace TPLscalarProd
{
class Program
{
static void Main()
{
double[] x = new double[] { 1, -5, 4, -7, 8, -15, 3, 2, -2, 1 };
int n = x.Length;
int m = n / 2;
double p1 = 0,p2=0;
Parallel.For(0, 2, i =>
{ if (i == 0) { 1 поток действия для вашего варианта };
if (i == 1) { 2 поток действия для вашего варианта}); }
Console.WriteLine("р1: " + (p1));
Console.WriteLine("р2: " + (p2));
Console.WriteLine("Норма вектора: " + (p1 + p2));
Console.ReadLine();
} } }
тут вроде правильно но не до конца нужно еще сложить элементы произведения наверно
ПРОСТИТЕ НЕ ТО СКИНУЛ, КАК МНЕ ЭТО ВСЕ СЛОЖИТЬ???или я не правильно по заданию делаю?помогите кто разбирается(((
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultVectors
{
class Program
{
static int[] vector1 = new int[4] { 1, 2, 3, 4 };
static int[] vector2 = new int[4] { 5, 6, 7, 8 };
static int[] vector3 = new int[4];
public static void Main(string[] args)
{
Parallel.For(0, 4, Vect);
Console.ReadLine();
}
static void Vect(int x)
{
Console.WriteLine("x=" + x);
vector3[x] = vector1[x] * vector2[x];
Console.WriteLine("Выполняется задача {0}", Task.CurrentId);
for (var i = 0; i < vector1.Length; i++)
{
Console.WriteLine(vector1[i] + "*" + vector2[i] + "=" + vector3[i]);А
}
Console.WriteLine(" ");
Console.ReadKey();
int[] z = new int[5];
Console.WriteLine("Massivtin kosindisin esepteu!!!");
for (int i = 0; i < 5; i++)
{
Console.Write("Z[{0}]=", i);
z[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
for (int i = 0; i < 5; i++)
{
sum = z[i] + sum;
}
Console.Write("sum = {0}", sum);
}
}
}Решение задачи: «Вычислить скалярное произведение векторов методом parallel.for»
textual
Листинг программы
int n = 100;
int[] v1 = new int[n]; // !
int[] v2 = new int[n]; // !
int dotProd = 0;
object lockObject = new object();
Parallel.For(0, n,
() => 0,
(i, state, partialSum) => {
Console.WriteLine("{0}'е компоненты умножаются в потоке #{1}",
i, Thread.CurrentThread.ManagedThreadId);
return partialSum + v1[i] * v2[i];
},
(partialSum) => { lock (lockObject) {
Console.WriteLine("Поток #{0} прибавляет свой результат к сумме",
Thread.CurrentThread.ManagedThreadId);
dotProd += partialSum;
} });
Console.WriteLine("Ответ: " + dotProd);