Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace ConsoleApp19
- {
- class Program
- {
- public static int[] A;
- public static int countNumbers;
- public static int countThread;
- public static object Locker = new object();
- public static int subArrayLen;
- public static int result = 0;
- static void Main(string[] args)
- {
- Console.Write("Количество цифр: ");
- if (int.TryParse(Console.ReadLine(), out countNumbers) == false || countNumbers < 1)
- {
- countNumbers = 10;
- Console.WriteLine($"Нельзя такое писать,количество чисел - {countNumbers}");
- }
- A = new int[countNumbers];
- Console.WriteLine("Задать числам значение:");
- UserFillA(ref A);
- Console.WriteLine("A: ");
- for (int i = 0; i < countNumbers; i++)
- Console.Write($"{A[i]} ");
- Console.Write("\nКоличество потоков: ");
- if (int.TryParse(Console.ReadLine(), out countThread) == false || countThread < 1)
- {
- countThread = 1;
- Console.WriteLine($"Нельзя такое писать, количество потоков - {countThread}");
- }
- if (countThread > countNumbers)
- {
- countThread = countNumbers;
- Console.WriteLine("Слишком много потоков, количество потоков - {count}");
- }
- subArrayLen = countNumbers / countThread + 1;
- Thread[] threads = new Thread[countThread];
- StartAllThreads(ref threads);
- WaitAllThreads(ref threads);
- Console.WriteLine($"Количество элементов кратных пяти: {result}");
- Console.ReadLine();
- }
- private static void WaitAllThreads(ref Thread[] threads)
- {
- foreach (Thread item in threads)
- {
- Console.WriteLine($"{item.Name} - enabled");
- item.Join();
- Console.WriteLine($"{item.Name} - switched off");
- }
- }
- private static void StartAllThreads(ref Thread[] threads)
- {
- for (int i = 0; i < countThread; i++)
- {
- PartArray partArray = new PartArray
- {
- StartIndex = i * subArrayLen,
- EndIndex = (i + 1) * subArrayLen
- };
- if (partArray.EndIndex > countNumbers)
- partArray.EndIndex = countNumbers;
- threads[i] = new Thread(() => SumWith3(partArray));
- threads[i].Name = $"Поток№{i + 1}";
- threads[i].Start();
- }
- }
- private static void UserFillA(ref int[] array)
- {
- for (int i = 0; i < array.Length; i++)
- {
- Console.Write($"{i + 1}:");
- if (int.TryParse(Console.ReadLine(), out array[i]) == false || array[i] < 1)
- {
- Console.WriteLine("Неправильный ввод");
- i--;
- }
- }
- }
- private static void SumWith3(PartArray partArray)
- {
- int start = partArray.StartIndex;
- int end = partArray.EndIndex;
- for (int i = start; i < end; i++)
- {
- if (A[i] % 5 == 0)
- lock (Locker)
- result++;
- }
- }
- }
- class PartArray
- {
- public int StartIndex;
- public int EndIndex;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment