Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Threading;
- using System.Threading.Channels;
- namespace DataStructuresAlgorithms.ParallelCourseWork
- {
- public class Parallel
- {
- public static bool IsPrime(int number)
- {
- const int threadCount = 4;
- var threads = new Thread[threadCount];
- var parameters = new Parameters[threadCount];
- var square = (int) Math.Sqrt(number);
- var intervalWidth = (square - 2) / threadCount;
- for (var i = 0; i < threadCount; i++)
- {
- var threadStart = new ParameterizedThreadStart(Routine);
- parameters[i] = new Parameters
- {
- Start = i == 0 ? 2 : intervalWidth * i,
- End = intervalWidth * (i + 1),
- Number = number
- };
- threads[i] = new Thread(threadStart);
- threads[i].Start(parameters[i]);
- }
- foreach (var thread in threads)
- {
- thread.Join();
- }
- var result = parameters.Aggregate((bool?) null, (current, parameter) => current == null ? parameter.Result : current.Value && parameter.Result.Value);
- return result.Value;
- }
- private static void Routine(object parameters)
- {
- var p = parameters as Parameters;
- var d = p.Start;
- while (d <= p.End)
- {
- if (p.Number % d == 0)
- {
- p.Result = false;
- return;
- }
- d++;
- }
- p.Result = true;
- }
- public class Parameters
- {
- public int Start { get; set; }
- public int End { get; set; }
- public int Number { get; set; }
- public bool? Result { get; set; }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement