public virtual void Speak(string message, bool async) { tts.SayTextRequest streq = new tts.SayTextRequest(); streq.SpeechText = message; if (async) { ttsPort.SayText(streq); } else { AutoResetEvent aevent = new AutoResetEvent(false); Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice(ttsPort.SayText(streq), delegate(DefaultUpdateResponseType state) { aevent.Set(); }, delegate(Fault f) { aevent.Set(); } )); aevent.WaitOne(1000, false); } }
public void StartScripting() { pe = new PythonEngine(); pe.Sys.path.Add(Myro.Utilities.Params.BinPath); //pe.Sys.path.Add(Myro.Utilities.Params.PythonPath); //pe.Sys.path.Add("C:\\Users\\t-richr\\Myro-dev\\richard-dev-2\\Frontend\\Python"); //pe.Import("site"); var s = new AnonymousPipeServerStream(PipeDirection.In); stdout = s; stdoutpipe = new AnonymousPipeClientStream(PipeDirection.Out, s.ClientSafePipeHandle); readThreadOut = new Thread(new ThreadStart(delegate() { readLoop(stdout, Colors.Black); })); readThreadOut.Start(); var e = new AnonymousPipeServerStream(PipeDirection.In); stderr = e; stderrpipe = new AnonymousPipeClientStream(PipeDirection.Out, e.ClientSafePipeHandle); readThreadErr = new Thread(new ThreadStart(delegate() { readLoop(stderr, Colors.Crimson); })); readThreadErr.Start(); commandQueue = new Port <string>(); commandDispatcherQueue = new DispatcherQueue("Python command queue", new Dispatcher(1, "Python command queue")); Arbiter.Activate(commandDispatcherQueue, Arbiter.Receive(true, commandQueue, commandHandler)); pe.SetStandardOutput(stdoutpipe); pe.SetStandardError(stderrpipe); historyBlock.Document.PageWidth = historyBlock.ViewportWidth; historyBlock.Document.Blocks.Clear(); paragraph = new Paragraph(); historyBlock.Document.Blocks.Add(paragraph); historyBlock.IsEnabled = true; }
public void beep(float duration, float frequency1, float frequency2) { bool flag = false; tonegen.PlayTone2Request request = new tonegen.PlayTone2Request(); request.Duration = (int)duration; request.Frequency1 = (int)frequency1; request.Frequency2 = (int)frequency2; tonegen.PlayTone2 ptone = new tonegen.PlayTone2(request); tonePort.Post(ptone); Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <DefaultUpdateResponseType>(false, ptone.ResponsePort, delegate(DefaultUpdateResponseType state) { flag = true; } )); while (!flag) { ; } }
public override void SetMotors(float leftPower, float rightPower) { if (!motorsOn) { EnableMotors(); } drive.SetDrivePowerRequest drivePowerReq = new drive.SetDrivePowerRequest(); drivePowerReq.LeftWheelPower = leftPower; drivePowerReq.RightWheelPower = rightPower; drive.SetDrivePower setDrivePower = new drive.SetDrivePower(drivePowerReq); drivePort.Post(setDrivePower); bool done = false; Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <DefaultUpdateResponseType>(false, setDrivePower.ResponsePort, delegate(DefaultUpdateResponseType state) { done = true; } )); while (!done) { ; } }
public void ParallelMul() { InputData[] data = new InputData[nc]; //назначение задач на кждый поток for (int i = 0; i < nc; ++i) { data[i] = new InputData(); data[i].a = a + i * (parts / nc) * h; data[i].steps = parts / nc; } Dispatcher d = new Dispatcher(nc, "Test Pool"); DispatcherQueue dq = new DispatcherQueue("Test Queue", d); Port <double> p = new Port <double>(); for (int i = 0; i < nc; i++) { Arbiter.Activate(dq, new Task <InputData, Port <double> >(data[i], p, Mul)); } Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(double[] array) { for (int i = 0; i < array.GetLength(0); ++i) { result += array[i]; } Console.WriteLine("Последовательный результат: {0}", planeResult); Console.WriteLine("Параллельный результат: {0}", result); })); }
protected void setGuiCurrentProximity(proxibrick.ProximityDataDssSerializable dir) { if (_mainWindow != null) { ccrwpf.Invoke invoke = new ccrwpf.Invoke( delegate() { _mainWindow.CurrentProximity = new ProximityData() { TimeStamp = dir.TimeStamp.Ticks, mbbl = dir.mbbl, mbbr = dir.mbbr, mbl = dir.mbl, mbr = dir.mbr, mffl = dir.mffl, mffr = dir.mffr, mfl = dir.mfl, mfr = dir.mfr }; } ); wpfServicePort.Post(invoke); Arbiter.Activate(TaskQueue, invoke.ResponsePort.Choice( s => { }, // delegate for success ex => { } //Tracer.Trace(ex) // delegate for failure )); } }
protected void setGuiCurrentParkingSensor(proxibrick.ParkingSensorDataDssSerializable dir) { if (_mainWindow != null) { ccrwpf.Invoke invoke = new ccrwpf.Invoke( delegate() { _mainWindow.CurrentParkingSensor = new ParkingSensorData() { TimeStamp = dir.TimeStamp.Ticks, parkingSensorMetersLB = dir.parkingSensorMetersLB, parkingSensorMetersLF = dir.parkingSensorMetersLF, parkingSensorMetersRB = dir.parkingSensorMetersRB, parkingSensorMetersRF = dir.parkingSensorMetersRF }; } ); wpfServicePort.Post(invoke); Arbiter.Activate(TaskQueue, invoke.ResponsePort.Choice( s => { }, // delegate for success ex => { } //Tracer.Trace(ex) // delegate for failure )); } }
private void startServices() { // Build a list of the "StartService"s and the "Adapter" services List <ServiceInfoType> allServices = new List <ServiceInfoType>(services); foreach (var adapter in adapterNames.Values) { if (adapter.ServiceConfig.Contract != null) { allServices.Add(adapter.ServiceConfig); } } // Start them all foreach (var service in allServices) { if (service.Contract != null) { Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice <CreateResponse, Fault>( DssEnvironment.CreateService(service), delegate(CreateResponse success) { Console.WriteLine("* Created * " + success.Service); }, delegate(Fault failure) { Console.WriteLine("*** FAULT *** creating " + service.Service + ": " + failure.Reason); })); } } }
/// <summary> /// This method searches for a primary or alternate contract of the /// service that is present in the contracts list. Requires a /// taskQueue to activate tasks on. Throws NoContractFoundException /// in a Fault if one cannot be found. /// </summary> /// <param name="taskQueue"></param> /// <param name="service"></param> /// <param name="contracts"></param> /// <returns></returns> public static PortSet <ServiceInfoType, Fault> FindCompatibleContract(DispatcherQueue taskQueue, Uri service, List <string> contracts) { PortSet <ServiceInfoType, Fault> returnPort = new PortSet <ServiceInfoType, Fault>(); PortSet <LookupResponse, Fault> responsePort = new PortSet <LookupResponse, Fault>(); //Console.WriteLine("RSUtils: Querying " + service); DssEnvironment.ServiceForwarderUnknownType(service).PostUnknownType( new DsspDefaultLookup() { Body = new LookupRequestType(), ResponsePort = responsePort }); Arbiter.Activate(taskQueue, Arbiter.Choice <LookupResponse, Fault>( responsePort, delegate(LookupResponse resp) { try { //Console.WriteLine("RSUtils: Got response"); returnPort.Post(FindCompatibleContract(resp, contracts)); } catch (NoContractFoundException e) { returnPort.Post(FaultOfException(e)); } }, delegate(Fault failure) { returnPort.Post(failure); })); return(returnPort); }
private void onInitialized(object sender, EventArgs e) { taskQueue = new DispatcherQueue("DriveControl", new Dispatcher(1, "DriveControl"), TaskExecutionPolicy.ConstrainQueueDepthDiscardTasks, 1); Arbiter.Activate(taskQueue, Arbiter.Receive(true, drivePort, driveHandler)); UpdateJoystickAxes(new game.Axes()); }
/// <summary> /// Overrides RobotBrain Bind function to implement addition LEDAdapter functions. /// </summary> protected override void Bind() { base.Bind(); //Bind to scribbler specific sensors //Specialized LED array directory.Query dquery = new directory.Query(new directory.QueryRequestType( new Microsoft.Dss.ServiceModel.Dssp.ServiceInfoType("http://www.roboteducation.org/scribblerledarray.html"))); //Uri direcURI = DssEnvironment.FindService(directory.Contract.Identifier); //TODO: remove the line below once the above line works Uri direcURI = new Uri("http://localhost:" + httpPort + "/directory"); directory.DirectoryPort dport = DssEnvironment.ServiceForwarder <directory.DirectoryPort>(direcURI); dport.Post(dquery); Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice(dquery.ResponsePort, delegate(directory.QueryResponseType success) { sledadapter = new ScribblerLEDArrayAdapter(success.RecordList[0].Service); }, delegate(Fault fault) { } ) ); }
private void subscribeCamera(CameraInfo argCi) { // Subscribe to the simulator camera, using a handler // that will only update the GUI if this camera is // selected (because there is currently no way to // unsubscribe from a camera. //if (ci.Camera.IsRealTimeCamera) //{ CameraInfo ci = argCi; ci.Port = new Port <System.Drawing.Bitmap>(); ci.Camera.Subscribe(ci.Port); Interleave interleave = new Interleave(new ExclusiveReceiverGroup(), new ConcurrentReceiverGroup()); interleave.CombineWith( new Interleave(new ExclusiveReceiverGroup( Arbiter.Receive(true, ci.Port, delegate(System.Drawing.Bitmap inbmp) { if (interleave.PendingExclusiveCount <= 1 && curCamera == ci) { if (DateTime.Now.Subtract(lastFrameTime).Milliseconds >= frameInterval) { lastFrameTime = DateTime.Now; updateImageDisplay(inbmp); } } })), new ConcurrentReceiverGroup())); Arbiter.Activate(throttledQueue, interleave); //} //else //{ // // If it's not a real time camera, we have to start a loop // // to query it // new Thread(new ThreadStart(delegate() // { // var resultPort = new PortSet<System.Drawing.Bitmap, Exception>(); // while (shouldStay) // { // if (curCamera == ci) // { // // The throttledQueue has only 1 thread, so concurrent execution // // will not happen here if the updateImageDisplay handler cannot // // keep up with the rate at which we're querying frames. // ci.Camera.CaptureScene(System.Drawing.Imaging.ImageFormat.Bmp, resultPort); // Arbiter.Activate(throttledQueue, Arbiter.Choice(resultPort, // updateImageDisplay, // delegate(Exception e) // { // Console.WriteLine(e); // })); // } // Thread.Sleep(frameInterval); // } // })).Start(); //} }
public void ParallelShell() { processes = new InputData[nc]; Console.WriteLine("Параллельная сортировка"); //Console.WriteLine("Массив до сортировки:"); //Display(0, partSize * nc); int c = -1; for (int i = 0; i < nc; i++) { processes[i] = new InputData(); processes[i].start = c + 1; processes[i].stop = c + partSize - 1; c += partSize - 1; } dq = new DispatcherQueue("Queue", d); p1 = new Port <int>(); for (int i = 0; i < nc; i++) { Arbiter.Activate(dq, new Task <InputData, Port <int> >(processes[i], p1, FirstPhase)); } // Все потоки завершили работу, финальная сортировка Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p1, nc, delegate(int[] array) { Stopwatch sw = new Stopwatch(); Console.WriteLine("Финальная сортировка"); sw.Start(); //int inner, temp; //for (int i = 0; i < partSize * nc; i++) //{ // temp = dataArray[i]; // inner = i; // while (inner > 0 && dataArray[inner - 1] >= temp) // { // dataArray[inner] = dataArray[inner - 1]; // inner--; // } // dataArray[inner] = temp; //} Array.Sort(dataArray); sw.Stop(); Console.WriteLine("Финальная сортировка заняла {0} мс", sw.ElapsedMilliseconds.ToString()); //Console.WriteLine("Результат:"); //Display(0, nc * partSize); } )); }
static void paral_qsort(int[] a, int left, int right) { int l = left; int r = right; int val = 0; int mid = a[(l + r) / 2]; while (l <= r) { while ((a[l] < mid) && (l <= right)) { l++; } while ((a[r] > mid) && (r >= left)) { r--; } if (l <= r) { val = a[l]; a[l] = a[r]; a[r] = val; l++; r--; } } InputData data1 = new InputData(); InputData data2 = new InputData(); if (r > left) { data1.str = "Нить исполнения 1"; data1.array = a; data1.start = left; data1.stop = r; //qsort(a, left, r); } if (l < right) { data2.str = "Нить исполнения 2"; data2.array = a; data2.start = l; data2.stop = right; //qsort(a, l, right); } //Создаём диспетчеры Dispatcher d = new Dispatcher(2, " Test Pool"); DispatcherQueue dq = new DispatcherQueue(" Test Queue", d); //Описываем порт Port <int> p = new Port <int>(); Arbiter.Activate(dq, new Task <InputData, Port <int> >(data1, p, thread_fun)); Arbiter.Activate(dq, new Task <InputData, Port <int> >(data2, p, thread_fun)); return; }
private void addCameraWatch(string cameraName, bool selectIfFound) { Delegate subscribeForEntity = new ThreadStart(delegate() { try { SimulationEngine.GlobalInstancePort.Subscribe(new EntitySubscribeRequestType() { Name = cameraName }, _notifyTarget); Arbiter.Activate(queue, Arbiter.Receive <InsertSimulationEntity>(true, _notifyTarget, delegate(InsertSimulationEntity ins) { AddCamera(ins.Body as CameraEntity, selectIfFound); })); } catch (Exception e) { Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new ThreadStart(delegate() { GUIUtilities.ReportUnexpectedException(e); })); } }); if (_notifyTarget != null && SimulationEngine.GlobalInstancePort != null) { Arbiter.Activate(queue, Arbiter.Choice( SimulationEngine.GlobalInstancePort.Query( new VisualEntity() { EntityState = new EntityState() { Name = cameraName } }), delegate(QuerySimulationEntityResponseType r) { if (r.Entity != null) { var cam = r.Entity as CameraEntity; if (cam != null) { AddCamera(cam, selectIfFound); } else { subscribeForEntity.DynamicInvoke(); } } else { subscribeForEntity.DynamicInvoke(); } }, delegate(Fault f) { subscribeForEntity.DynamicInvoke(); })); } }
private void Initialize() { // using the supplied taskQueue for scheduling, activate three // persisted receivers, that will run concurrently to each other, // one for each item type Arbiter.Activate(_taskQueue, Arbiter.Receive <UpdateState>(true, _mainPort, UpdateHandler), Arbiter.Receive <GetState>(true, _mainPort, GetStateHandler) ); }
protected override void Start() { base.Start(); int parts = (int)((b - a) / h); System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch(); sp.Start(); for (int i = 0; i < parts - 1; i += 2) { planeResult += Integral(a + i * h, a + (i + 1) * h); } sp.Stop(); string planeTime = sp.ElapsedMilliseconds.ToString(); int nc = 2; InputData[] data = new InputData[nc]; for (int i = 0; i < nc; ++i) { data[i] = new InputData(); data[i].a = a + i * (parts / nc) * h; data[i].steps = parts / nc; } Dispatcher d = new Dispatcher(4, "Test Pool"); DispatcherQueue dq = new DispatcherQueue("Test Queue", d); Port <double> port = new Port <double>(); for (int i = 0; i < nc; i++) { Arbiter.Activate(dq, new Task <InputData, Port <double> >(data[i], port, Calc)); } Arbiter.Activate(Environment.TaskQueue, Arbiter.MultipleItemReceive(true, port, nc, delegate(double[] array) { for (int i = 0; i < array.GetLength(0); ++i) { result += array[i]; } Console.WriteLine("Plane result: {0}", planeResult); Console.WriteLine("Parallel result: {0}", result); Console.WriteLine("Computations completed"); Console.WriteLine("Linear calculation time: {0}ms", planeTime); })); }
public ThrottledQueue(string threadPoolName, string dispatcherQueueName, PostMessageDelegate postMessage, int maxPoolItemReuse) { matchMaker = new MatchMaker(maxPoolItemReuse); dispatcher = new Dispatcher(1, threadPoolName); dispatcherQueue = new DispatcherQueue(dispatcherQueueName, dispatcher); messagePort = new Port <QueueItem>(); Handler <QueueItem> handler = new Handler <QueueItem>(postMessage); Arbiter.Activate(dispatcherQueue, Arbiter.Receive(true, messagePort, handler)); }
static void Main(string[] args) { nc = 2; m = 1025; A = new double[m]; B = new double[m]; System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch(); sWatch.Start(); for (int i = 0; i < m; i++) { A[i] = Math.Sin((2 * i * Math.PI) / 1024); } sWatch.Stop(); Console.WriteLine(A[0]); Console.WriteLine(A[1]); Console.WriteLine(A[511]); Console.WriteLine(A[512]); Console.WriteLine(A[513]); Console.WriteLine(A[1023]); Console.WriteLine(A[1024]); Console.WriteLine(" Sequential algorithm = {0} t. ", sWatch.ElapsedTicks); InputData[] ClArr = new InputData[nc]; for (int i = 0; i < nc; i++) { ClArr[i] = new InputData(); } int step = (Int32)(m / nc); int c = -1; for (int i = 0; i < nc; i++) { ClArr[i].start = c + 1; ClArr[i].stop = c + step; c = c + step; } Dispatcher d = new Dispatcher(nc, " Test Pool "); DispatcherQueue dq = new DispatcherQueue(" Test Queue", d); Port <int> p = new Port <int>(); for (int i = 0; i < nc; i++) { Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, sinus)); } Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array) { Console.WriteLine(B[0]); Console.WriteLine(B[1]); Console.WriteLine(B[511]); Console.WriteLine(B[512]); Console.WriteLine(B[513]); Console.WriteLine(B[1023]); Console.WriteLine(B[1024]); })); }
private void Initialize() { // Activate three persisted receivers (single item arbiters) // that will run concurrently to each other, // one for each item/message type Arbiter.Activate(_taskQueue, Arbiter.Receive <int>(true, _mainPort, IntWriteLineHandler), Arbiter.Receive <string>(true, _mainPort, StringWriteLineHandler), Arbiter.Receive <double>(true, _mainPort, DoubleWriteLineHandler) ); }
protected virtual void Initialize() { // Initialize the port and subscribe to the service motorsOn = false; drivePort = DssEnvironment.ServiceForwarder <drive.DriveOperations>(new Uri(ServiceInfo.Service)); drive.DriveOperations driveNotificationPort = new drive.DriveOperations(); drivePort.Subscribe(driveNotificationPort); // Set up notifications Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <drive.Update>(true, driveNotificationPort, NotifyDriveUpdate)); }
protected virtual void Initialize() { // Initialize the port and subscribe to the service to know when the motors are enabled motorsOn = false; drivePort = DssEnvironment.ServiceForwarder <drive.DriveOperations>(new Uri(ServiceInfo.Service)); drive.DriveOperations driveNotificationPort = new drive.DriveOperations(); RSUtils.ReceiveSync(taskQueue, drivePort.Subscribe(driveNotificationPort), Params.DefaultRecieveTimeout); // Set up notifications Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <drive.Update>(true, driveNotificationPort, NotifyDriveUpdate)); }
public void PlaySong(MyroInterfaces.IMyroSong song) { MyroSong msong = (MyroSong)song; foreach (MyroSong.ListItem li in msong.songSequence) { if (li.chord) { tonegen.PlayTone2Request request = new tonegen.PlayTone2Request(); request.Duration = (int)(li.duration * 1000f); request.Frequency1 = (int)li.frequency1; request.Frequency2 = (int)li.frequency2; tonegen.PlayTone2 ptone = new tonegen.PlayTone2(request); tonePort.Post(ptone); bool done = false; Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <DefaultUpdateResponseType>(false, ptone.ResponsePort, delegate(DefaultUpdateResponseType state) { done = true; } )); while (!done) { ; } } else { tonegen.PlayToneRequest request = new tonegen.PlayToneRequest(); request.Duration = (int)(li.duration * 1000f); request.Frequency = (int)li.frequency1; tonegen.PlayTone ptone = new tonegen.PlayTone(request); tonePort.Post(ptone); bool done = false; Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <DefaultUpdateResponseType>(false, ptone.ResponsePort, delegate(DefaultUpdateResponseType state) { done = true; } )); while (!done) { ; } } } }
protected virtual void InternalProcessQueue() { Receiver <T> receiver = Arbiter.Receive <T>(true, this.port, delegate(T item) { this.QueueHandler(item); } ); Arbiter.Activate(this.dispatcherQueue, new ITask[] { receiver }); }
static void ParallelMul() { // создание массива объектов для хранения параметров InputData[] ClArr = new InputData[nc]; for (int i = 0; i < nc; i++) { ClArr[i] = new InputData(); } //Далее, задаются исходные данные для каждого экземпляра //вычислительного метода: // делим количество строк в матрице на nc частей int step = (Int32)(m / nc); // заполняем массив параметров int c = -1; for (int i = 0; i < nc; i++) { ClArr[i].start = c + 1; ClArr[i].stop = c + step; c = c + step; } //Создаётся диспетчер с пулом из двух потоков: Dispatcher d = new Dispatcher(nc, "Test Pool"); DispatcherQueue dq = new DispatcherQueue("Test Queue", d); //Описывается порт, в который каждый экземпляр метода Mul() //отправляет сообщение после завершения вычислений: Port <int> p = new Port <int>(); //Метод Arbiter.Activate помещает в очередь диспетчера две задачи(два //экземпляра метода Mul): for (int i = 0; i < nc; i++) { Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, Mul)); } //Первый параметр метода Arbiter.Activate – очередь диспетчера, //который будет управлять выполнением задачи, второй параметр – //запускаемая задача. //С помощью метода Arbiter.MultipleItemReceive запускается задача //(приёмник), которая обрабатывает получение двух сообщений портом p: Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array) { dispResult(); Console.WriteLine("Вычисления завершены"); Console.ReadKey(true); Environment.Exit(0); })); }
protected virtual void ActivateProcessQueue() { Arbiter.Activate(this.dispatcherQueue, new ITask[] { Arbiter.MultipleItemReceive <T>(true, this.port, this.activateItems, delegate(T[] items) { for (int i = 0; i < items.Length; i++) { T item = items[i]; this.QueueHandler(item); } } ) }); }
private void InitQueue(string queueName, QueueItemHandler queueItemHandler, int threadCount, ThreadPriority threadPriority, int maxItemsInMemory, int dequeueInterval, int dequeueBatch, string persistPath) { this.queueName = queueName; this.queueItemHandler = queueItemHandler; this.persistence = new EfzQueuePersistence <T>(persistPath); this.dequeueInterval = dequeueInterval; this.dequeueBatch = dequeueBatch; this.dispatcher = new Dispatcher(threadCount, threadPriority, true, "Thread Pool - " + queueName); this.queue = new DispatcherQueue(queueName, this.dispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, maxItemsInMemory); Arbiter.Activate(this.queue, new ITask[] { Arbiter.Receive <PersistentQueueItem <T> >(true, this.port, new Handler <PersistentQueueItem <T> >(this.InternalQueueItemHandler)) }); this.dequeueTimer = new Timer(new TimerCallback(this.Dequeue), null, -1, -1); }
//Метод параллельной сортировки массива static void parral_qsort(int[] a, int left, int right) { //Создаём диспетчеры Dispatcher d = new Dispatcher(2, " Test Pool"); DispatcherQueue dq = new DispatcherQueue(" Test Queue", d); //Описываем порт Port <int> p = new Port <int>(); //Первый этап параллельной сортировки //Параллельно сортируются две половины массива InputData data = new InputData(); data.str = "Первая половина массива "; data.array = a; data.start = 0; data.stop = right / 2 + 1; Arbiter.Activate(dq, new Task <InputData, Port <int> >(data, p, thread_fun)); Console.WriteLine("Первый этап"); Console.ReadKey(); data.str = "Вторая половина массива "; data.array = a; data.start = right / 2 + 1; data.stop = right; Arbiter.Activate(dq, new Task <InputData, Port <int> >(data, p, thread_fun)); Console.ReadKey(); //Второй этап параллельной сортировки //Сортируется центральная часть массива Console.WriteLine(); Console.WriteLine("Второй этап"); Stopwatch sWatch = new Stopwatch(); sWatch.Start(); qsort(a, right / 4, right / 4 + right / 2 + 1); sWatch.Stop(); Console.WriteLine("Средняя часть массива Время работы: " + sWatch.ElapsedMilliseconds); Console.ReadKey(); //Третий этап параллельной сортировки //Параллельно сортируются две половины массива data.str = "Первая половина массива "; data.array = a; data.start = 0; data.stop = right / 2 + 1; Arbiter.Activate(dq, new Task <InputData, Port <int> >(data, p, thread_fun)); Console.WriteLine("Первый этап"); Console.ReadKey(); data.str = "Вторая половина массива "; data.array = a; data.start = right / 2 + 1; data.stop = right; Arbiter.Activate(dq, new Task <InputData, Port <int> >(data, p, thread_fun)); Console.ReadKey(); return; }
static void ParallelShellSort() { Dispatcher dispatcher = new Dispatcher(arraySize, "THREAD_POOL"); DispatcherQueue dsipQueue = new DispatcherQueue("Dispatcher", dispatcher); Port <int> port = new Port <int>(); for (int i = 0; i < arraySize; ++i) { Data d = new Data(); d.row = i; Arbiter.Activate(dsipQueue, new Task <Data, Port <int> >(d, port, Task)); } return; }
//Метод, осуществляющий запуск параллельного алгоритма сортировки слиянием. //Результат - время подготовки необходимого для запуска асинхронных //вычислений и разбиения задачи на подзадачи. public long workAsync() { Stopwatch watcher = new Stopwatch(); // вычисление полного времени вычислений watcher.Start(); InputData[] ClArr = new InputData[processCount]; // Создал хранилище начальных данных для подзадач for (int i = 0; i < processCount; i++) { ClArr[i] = new InputData(); } int step = (Int32)(itemCount / processCount); // Размер данных int c = -1; for (int i = 0; i < processCount; i++) // Заполнил хранилище исходными данными { ClArr[i].start = c + 1; ClArr[i].stop = c + step; c += step; } // Создадим диспетчер задач Dispatcher d = new Dispatcher(processCount, "Test Pool"); DispatcherQueue dq = new DispatcherQueue("Test Queue", d); // Определим экземпляр порта Port <int> port = new Port <int>(); // Заполняем диспетчер задачами for (int i = 0; i < processCount; i++) { Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], port, sort)); } // Зададим задачу, которая будет выполнена после выполнения всех остальных задач Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, port, processCount, delegate(int[] array) { // Проведем окончательно слияние 2 отсортированных подмасива MainMerge(raw, 0, (itemCount - 1) / 2 + 1, itemCount - 1); watcher.Stop(); // Выведем сообщение об времени выполнения алгоритма Console.WriteLine("Общее время выполнения: " + watcher.ElapsedMilliseconds); } )); return(watcher.ElapsedMilliseconds); }