Anonim_999

kir

Nov 19th, 2022 (edited)
730
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.96 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace ConsoleApp19
  5. {
  6.     class Program
  7.     {
  8.         public static int CountElements;
  9.         public static int ThreadCount;
  10.         public static int[] arrayNumbers;
  11.         public static bool oper = true;
  12.         public static int result = 0;
  13.         public static object Locker = new object();
  14.         public static int TempEndIndex = 0;
  15.  
  16.         static void Main(string[] args)
  17.         {
  18.             int subArrayLenght = 0;
  19.             string userInput;
  20.             Random random = new Random();
  21.             Console.WriteLine("Введите размер массива: ");
  22.  
  23.             if (!int.TryParse(Console.ReadLine(), out CountElements))
  24.             {
  25.                 Console.WriteLine("Ошибка, количество элементов стало стандартным - 10");
  26.                 CountElements = 10;
  27.             }
  28.             Console.WriteLine("Введите количество потоков: ");
  29.  
  30.             if (!int.TryParse(Console.ReadLine(), out ThreadCount))
  31.             {
  32.                 Console.WriteLine("Ошибка, количество потоков стало стандартным - 1");
  33.                 ThreadCount = 1;
  34.             }
  35.             arrayNumbers = new int[CountElements];
  36.             //Заполнение рандомом - работает!
  37.             /*for (int i = 0; i <= CountElements - 1; i++)
  38.                 arrayNumbers[i] = random.Next(1, 10);*/
  39.  
  40.             for (int i = 0; i < CountElements - 1; i++)
  41.             {
  42.                 Console.Write($"{i + 1} элемент:");
  43.                 userInput = Console.ReadLine();
  44.  
  45.                 if (!int.TryParse(userInput,out arrayNumbers[i]) || arrayNumbers[i] < 1)
  46.                 {
  47.                     Console.WriteLine("Ошибка,ввод только натуральные числа они должны быть больше нуля");
  48.                     i--;
  49.                 }
  50.             }
  51.             Console.ForegroundColor = ConsoleColor.Red;
  52.             Console.Write("Элементы массива: ");
  53.             Console.ResetColor();
  54.  
  55.             foreach (int item in arrayNumbers)
  56.             {
  57.                 Console.Write($"{item} ");
  58.             }
  59.  
  60.             if (ThreadCount <= 0)
  61.                 ThreadCount = 1;
  62.  
  63.             if (ThreadCount > CountElements)
  64.                 ThreadCount = CountElements;
  65.             subArrayLenght = CountElements / ThreadCount + 1;
  66.             Thread[] threads = new Thread[ThreadCount];
  67.             Console.WriteLine();
  68.  
  69.             for (int i = 0; i < ThreadCount; i++) // Создание потоков
  70.             {
  71.                 PartArray partArray = new PartArray
  72.                 {
  73.                     StartIndex = i * subArrayLenght,
  74.                     EndIndex = (i + 1) * subArrayLenght
  75.                 };
  76.                 Console.WriteLine($"ст: {partArray.StartIndex} | {partArray.EndIndex}");
  77.                 if (partArray.EndIndex > CountElements)
  78.                     partArray.EndIndex = CountElements;
  79.                 threads[i] = new Thread(() => EvaluateExpression(partArray)); //Передача метода потоку
  80.                 threads[i].Name = $"Поток №{i + 1}";
  81.             }
  82.             Console.WriteLine();
  83.  
  84.             for (int i = 0; i < ThreadCount; i++)
  85.             {
  86.                 Console.WriteLine($"{threads[i].Name} - запущен");
  87.                 threads[i].Start(); //Запуск потока
  88.                 threads[i].Join(); //Ожидание завершения потока
  89.                 Console.WriteLine($"{threads[i].Name} - завершил");
  90.             }
  91.             Console.WriteLine($"Результат: {result}");
  92.             Console.ReadLine();
  93.         }
  94.         static void EvaluateExpression(PartArray partArray) //Метод расчета
  95.         {
  96.             if (partArray == null) //Проверка на пустоту класса
  97.                 return;
  98.             int start = partArray.StartIndex;
  99.             int end = partArray.EndIndex;
  100.  
  101.             for (int i = start; i < end; i++)
  102.             {
  103.                 if (oper)
  104.                 {
  105.                     lock (Locker) //блокирует объекты, чтобы не было конфликтов с потоками
  106.                     {
  107.                         result += arrayNumbers[i];
  108.                         oper = false;
  109.                     }
  110.                 }
  111.                 else
  112.                 {
  113.                     lock (Locker)//блокирует объекты, чтобы не было конфликтов с потоками
  114.                     {
  115.                         result -= arrayNumbers[i];
  116.                         oper = true;
  117.                     }
  118.                 }
  119.             }
  120.         }
  121.     }
  122. }
  123.  
  124. public class PartArray //Класс для хранения интервала
  125. {
  126.     public int StartIndex;
  127.     public int EndIndex;
  128. }
Advertisement
Add Comment
Please, Sign In to add comment