Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace ConsoleApplication1
- {
- class Program
- {
- public static int[] A;
- public static int[] C;
- public static int countThread = 1;
- public static int subArrayLen;
- public static double countPairs = 0;
- public static object Locker = new object();
- public static int countElements;
- static void Main(string[] args)
- {
- Console.WriteLine("Количество элементов у массивов: ");
- if (!int.TryParse(Console.ReadLine(),out countElements) || countThread <= 0)
- {
- countElements = 10;
- Console.WriteLine($"Неравильный ввод. Количество элементов - {countElements}");
- }
- Console.WriteLine("Количество потоков: ");
- if (!int.TryParse(Console.ReadLine(), out countThread) || countThread <= 0)
- {
- countThread = 1;
- Console.WriteLine($"Нерпавильный ввод. Количество потоков - {countThread}");
- }
- if (countThread > countElements)
- {
- countThread = countElements;
- Console.WriteLine($"потоков больше чем элементов в массивах. Количество потоков - {countThread}");
- }
- A = new int[countElements];
- C = new int[countElements];
- FillArray(ref A);
- FillArray(ref C);
- Console.WriteLine("A:");
- ShowArray(A);
- Console.WriteLine("\nC:");
- ShowArray(C);
- Console.WriteLine();
- subArrayLen = countElements / countThread + 1;
- Thread[] threads = new Thread[countThread]; //Массив потоков
- for (int i = 0; i < countThread; i++)
- {
- PartArray partArray = new PartArray
- {
- StartIndex = i * subArrayLen,
- EndIndex = (i + 1) * subArrayLen
- };
- if (partArray.EndIndex > countElements)
- partArray.EndIndex = countElements;
- threads[i] = new Thread(() => СompareElements(partArray));
- threads[i].Name = $"Поток №{i + 1}";
- threads[i].Start();
- }
- foreach (Thread thread in threads)
- {
- Console.WriteLine($"{thread.Name} - запущен");
- thread.Join();
- Console.WriteLine($"{thread.Name} - звершил");
- }
- Console.WriteLine($"Количество пар где A > C: {countPairs}");
- Console.ReadKey();
- }
- private static void FillArray(ref int[] array)
- {
- Random random = new Random();
- for (int i = 0; i < array.Length; i++)
- {
- array[i] = random.Next(11);
- }
- }
- private static void ShowArray(int[] array)
- {
- foreach (int item in array)
- Console.Write($"{item} ");
- }
- private static void СompareElements(PartArray partArray)
- {
- int start = partArray.StartIndex;
- int end = partArray.EndIndex;
- for (int i = start; i < end; i++)
- if (A[i] > C[i])
- lock (Locker)
- countPairs++;
- }
- }
- class PartArray //индексы части массива
- {
- public int StartIndex;
- public int EndIndex;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment