private static void GenerateNumber() { _barrier.AddParticipant(); var random = new Random(); for (int i = 0; i < 6; i++) { _numbers.Add(random.Next()); } _barrier.SignalAndWait(); }
public void mehtod() { const int numberTasks = 2; const int partitionSize = 100000; const int loops = 5; var taskResults = new Dictionary <int, int[][]>(); var data = new List <string> [loops]; for (int i = 0; i < loops; i++) { data[i] = new List <string>(FillData(partitionSize * numberTasks)); } var barrier = new Barrier(numberTasks + 1); LogBarrierInformation("i", barrier); for (int i = 0; i < numberTasks; i++) { barrier.AddParticipant(); int jobnumber = i; taskResults.Add(i, new int[loops][]); for (int loop = 0; loop < loops; loop++) { //taskResults[i, loop]; } } }
/// <summary> /// Starts same task on each worker, each worker executes this task exactly once. /// Good for initialization and release of per-thread resources. /// THIS CANNOT BE RUN FROM ANY WORKER! /// </summary> public static void StartOnEachWorker(Action action, bool waitForCompletion = true) { System.Diagnostics.Debug.Assert(!Thread.CurrentThread.Name.Contains("Parallel", StringComparison.InvariantCultureIgnoreCase), "StartOnEachWorker cannot be called from worker thread"); Barrier barrier = new Barrier(Scheduler.ThreadCount); Action syncedAction = () => RunPerWorker(action, barrier); if (waitForCompletion) { barrier.AddParticipant(); Task[] tasks = new Task[Scheduler.ThreadCount]; for (int i = 0; i < Scheduler.ThreadCount; i++) { tasks[i] = Start(syncedAction); } barrier.SignalAndWait(); for (int i = 0; i < Scheduler.ThreadCount; i++) { tasks[i].Wait(); } } else { for (int i = 0; i < Scheduler.ThreadCount; i++) { Start(syncedAction); } } }
private void DownloadGDBFiles() { finishFirstGDBSemaphore = new SemaphoreSlim(1); //finishFirstGDBSemaphore.Wait(); Barrier downloadTrainingBarrier = new Barrier(1); foreach (int key in _currentTraining.Playlist.Keys) { Exercise exercise = _currentTraining.Playlist[key][1]; int newKey = key; if (exercise.IsTraceable && !exercise.Downloaded) { downloadTrainingBarrier.AddParticipant(); if (newKey == FIRST_EXERCISE) { finishFirstGDBSemaphore.Wait(); } Task downloadGDB = new Task(() => DownloadCurrentGDB(exercise, newKey, downloadTrainingBarrier)); downloadGDB.Start(); } } downloadTrainingBarrier.SignalAndWait(); _currentTraining.Downloaded = true; //watch.Stop(); //var elapsedMs = watch.ElapsedMilliseconds; //Console.WriteLine("==> Downloading gdb " + elapsedMs.ToString()); }
public void SignalSimple() { var barrier = new Barrier(0); barrier.AddParticipant(); Assert.IsTrue(barrier.SignalAndWait(500), "#1"); }
static void Main(String[] a) { Thread[] threads = new Thread[5]; TeamWorkBarrier tw = new TeamWorkBarrier(); Barrier barrier = new Barrier(5, (b) => { Console.WriteLine("Barrier Released" + b); } ); //barrier = new Barrier(5, tw.BarrierReleased); barrier.AddParticipant(); for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(tw.MyTurn); } for (int i = 0; i < threads.Length; i++) { threads[i].Start(barrier); } barrier.SignalAndWait(); Console.WriteLine("END"); List <int> lista = new List <int>(); for (int i = 0; i < 100; i++) { lista.Add(r.Next()); } int wynik = 0; lista.ForEach((x) => { wynik += x; }); Console.WriteLine(wynik); Console.ReadKey(); }
public static void RunBarrierTest7a() { for (int j = 0; j < 100; j++) { Barrier b = new Barrier(0); Action[] actions = new Action[4]; for (int k = 0; k < 4; k++) { actions[k] = (Action)(() => { for (int i = 0; i < 400; i++) { b.AddParticipant(); b.RemoveParticipant(); } }); } Task[] tasks = new Task[actions.Length]; for (int k = 0; k < tasks.Length; k++) { tasks[k] = Task.Factory.StartNew((index) => actions[(int)index](), k, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } Task.WaitAll(tasks); Assert.Equal(0, b.ParticipantCount); } }
public BarrierLimitedModeCharacterCounter(ITextFile textFile, Barrier barrier) { this.barrier = barrier; barrier.AddParticipant(); charCounts = new Lazy <IReadOnlyDictionary <char, int> >(() => BufferAndCount(textFile)); }
//public bool MainMenu(Controller controller) //{ // bool menu = true; // while(menu == true) // { // view.ShowMenu(controller); // } // return true; //} public void doFullSave(string source, string target) { FullSaveStrategy fullSaveStrategy = new FullSaveStrategy(); fullSaveStrategy.Save(source, target, MaxSizeSemaphore); Barrier.AddParticipant(); }
public void doDiffSave(string fullSaveDir, string source, string target) { DiffSaveStrategy diffSaveStrategy = new DiffSaveStrategy(fullSaveDir); diffSaveStrategy.Save(source, target, MaxSizeSemaphore); Barrier.AddParticipant(); }
public void AddParticipantTest() { barrier.AddParticipant(); Assert.AreEqual(participants + 1, barrier.ParticipantCount, "#1"); barrier.AddParticipants(3); Assert.AreEqual(participants + 4, barrier.ParticipantCount, "#2"); }
/// <summary> /// checkConnections periodically checks which connections should /// close due to timeouts. /// </summary> private void checkConnections() { wg.AddParticipant(); var ticker = new Timer((state) => { if (!IsLeader) { return; } var tmpConns = new List <StoreConnection>(); connsMu.EnterReadLock(); try { foreach (var c in conns.Values) { // Sometimes IDs are in the slice without a connection, if a // connection is in process of being formed via consensus. if (c == null || c.ID == defaultConnID) { continue; } if (c.IdleTimedOut() || c.TxTimedOut()) { tmpConns.Add(c); } } } finally { connsMu.ExitReadLock(); } foreach (var c in tmpConns) { try { c.Close(); logger.LogInformation($"{c} closed due to timeout"); // Only increment stat here to make testing easier. stats.NumConnTimeouts.WriteMetric(1); } catch (NotLeaderException) { // Not an issue, the actual leader will close it. continue; } catch (Exception ex) { logger.LogError($"{c} failed to close: {ex.Message}"); } } }, null, TimeSpan.Zero, connectionPollPeriod); done.Reader.WaitToReadAsync().AsTask().ContinueWith(_ => { wg.RemoveParticipant(); ticker.Change(Timeout.Infinite, Timeout.Infinite); }); }
public Player(EventWaitHandle wh) { Stack = new PlayerStack <CardBase>(); worker = new Thread(CheckCard); worker.Start(); this.wh = wh; barrier.AddParticipant(); }
static void Main() { const int numberTasks = 2; const int partitionSize = 1000000; const int loops = 5; var taskResults = new Dictionary <int, int[][]>(); var data = new List <string> [loops]; for (int i = 0; i < loops; i++) { data[i] = new List <string>(FillData(partitionSize * numberTasks)); } var barrier = new Barrier(1); LogBarrierInformation("initial participants in barrier", barrier); for (int i = 0; i < numberTasks; i++) { barrier.AddParticipant(); int jobNumber = i; taskResults.Add(i, new int[loops][]); for (int loop = 0; loop < loops; loop++) { taskResults[i][loop] = new int[26]; } Console.WriteLine($"Main - starting task job {jobNumber}"); Task.Run(() => CalculationInTask(jobNumber, partitionSize, barrier, data, loops, taskResults[jobNumber])); } for (int loop = 0; loop < 5; loop++) { LogBarrierInformation("main task, start signaling and wait", barrier); barrier.SignalAndWait(); LogBarrierInformation("main task waiting completed", barrier); // var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) => c1 + c2); int[][] resultCollection1 = taskResults[0]; int[][] resultCollection2 = taskResults[1]; var resultCollection = resultCollection1[loop].Zip(resultCollection2[loop], (c1, c2) => c1 + c2); char ch = 'a'; int sum = 0; foreach (var x in resultCollection) { Console.WriteLine($"{ch++}, count: {x}"); sum += x; } LogBarrierInformation($"main task finished loop {loop}, sum: {sum}", barrier); } Console.WriteLine("at the end"); Console.ReadLine(); }
/// <summary> /// BarrierDemoStart()方法创建一个Barrier实例。在构造函数中,可以指定参与者的数量。 /// 在该示例中,这个数量是3(numberTasks+1),因为该示例创建了两个任务,BarrierDemoStart()方法本身也是一个参与者。 /// 使用Task.Run创建两个任务,把遍历集合的任务分为两个部分。 /// 启动该任务后,使用SignalAndWait()方法,BarrierDemoStart()方法在完成时发出信号, /// 并等待所有其他参与者或者发出完成的信号,或者从Barrier类中删除它们。 /// 一旦所有的参与者都准备好,就提取任务的结果,并使用Zip()扩展方法把它们合并起来。接着进行下一次迭代,等待任务的下一个结果。 /// </summary> public static void BarrierDemoStart() { const int numberTasks = 2; const int partitionSize = 1000000; const int loops = 5; var taskResults = new Dictionary <int, int[][]>(); var data = new List <string> [loops]; for (int i = 0; i < loops; i++) { data[i] = new List <string>(FillData(partitionSize * numberTasks)); } var barrier = new Barrier(1); LogBarrierInformation("在barrier中初始化Participant", barrier); for (int i = 0; i < numberTasks; i++) { barrier.AddParticipant(); int jobNumber = i; taskResults.Add(i, new int[loops][]); for (int loop = 0; loop < loops; loop++) { taskResults[i][loop] = new int[26]; } Console.WriteLine($"BarrierDemoStart - 开始Task job{jobNumber}"); Task.Run(() => CalculationInTask(jobNumber, partitionSize, barrier, data, loops, taskResults[jobNumber])); } for (int loop = 0; loop < 5; loop++) { LogBarrierInformation("BarrierDemoStart task,开始发信号和等待", barrier); barrier.SignalAndWait(); LogBarrierInformation("BarrierDemoStart task,等待完成", barrier); // var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) => c1 + c2); int[][] resultCollection1 = taskResults[0]; int[][] resultCollection2 = taskResults[1]; var resultCollection = resultCollection1[loop].Zip(resultCollection2[loop], (c1, c2) => c1 + c2); char ch = 'a'; int sum = 0; foreach (var x in resultCollection) { Console.WriteLine($"{ch++},count:{x}"); sum += x; } LogBarrierInformation($"BarrierDemoStart task已完成loop{loop},sum:{sum}", barrier); } Console.WriteLine("已完成所有迭代"); Console.ReadLine(); }
public static void Run() { for (var i = 0; i < 5; i++) { _barrier.AddParticipant(); T(i); } Console.WriteLine("enter to signal"); var r = Console.ReadLine(); _barrier.SignalAndWait(); Console.Write("enter again quit"); Console.ReadLine(); }
public bool addGroup(GeneratedCpu g) { try { _b.AddParticipant(); _groupCpu.Add(g); g.enableBarrier(_b); return(true); } catch { return(false); } }
public static void Execute() { _barrierM2.AddParticipants(_participantsCount); _barrierM2.AddParticipant(); _barrierM2.RemoveParticipant(); var participants = new Thread[_participantsCount]; for (var i = 0; i < _participantsCount; i++) { participants[i] = new Thread(Foo) { Name = i.ToString() }; participants[i].Start(); } }
private static void CHANGE_CLIENT_COUNT(bool clientJoined) { lock (BARRIER_LOCK_OBJECT) { if (clientJoined) { CLIENT_BARRIER.AddParticipant(); } else { CLIENT_BARRIER.RemoveParticipant(); } //cancel the cancellation token that CLIENT_BARRIER observes CANCEL_SOURCE.Cancel(); //and also reset it so it doesn't do anything silly CANCEL_SOURCE = new CancellationTokenSource(); } }
public static void RunBarrierTest7a() { bool failed = false; for (int j = 0; j < 100 && !failed; j++) { Barrier b = new Barrier(0); Action[] actions = new Action[4]; for (int k = 0; k < 4; k++) { actions[k] = (Action)(() => { for (int i = 0; i < 400; i++) { try { b.AddParticipant(); b.RemoveParticipant(); } catch { failed = true; break; } } }); } Task[] tasks = new Task[actions.Length]; for (int k = 0; k < tasks.Length; k++) { tasks[k] = Task.Factory.StartNew((index) => actions[(int)index](), k, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } Task.WaitAll(tasks); if (b.ParticipantCount != 0) { failed = true; } } if (failed) { Assert.True(false, string.Format("BarrierTests: RunBarrierTest7a failed")); } }
static void Main(string[] args) { //var bankTerminal = new BankTerminal2(new IPEndPoint(new IPAddress(0x2414188f), 8080)); //var purchaseTask = bankTerminal.Purchase(100); //var firstContinuation = purchaseTask.ContinueWith(x => //{ // Console.WriteLine($"{x.Result} purchase done"); //}); //firstContinuation.ContinueWith(x => { // Console.WriteLine("-----------Another Operation-------------"); // var secondPurchaseTask = bankTerminal.Purchase(50); // secondPurchaseTask.ContinueWith(y => // { // Console.WriteLine($"{y.Result} purchase done"); // }); //}); //TestBankTerminal(); ///////////////////////////////////////////////// int totalRecords = GetNumberOfRecords(); Task[] tasks = new Task[totalRecords]; for (int i = 0; i < totalRecords; ++i) { Barrier.AddParticipant(); int j = i; tasks[j] = Task.Factory.StartNew(() => { GetDataAndStoreData(j); }); } Task.WaitAll(tasks); Console.WriteLine("Backup completed"); Console.Read(); }
private static void BarrierExample() { Task[] tasks = new Task[5]; for (int i = 0; i < 5; i++) { barrier.AddParticipant(); int index = i; tasks[index] = Task.Factory.StartNew(() => { GetDataAndStoreData(index); }); } Task.WaitAll(tasks); Console.WriteLine("Completed"); }
static void Main(string[] args) { int totalRecords = GetNumberOfRecords(); Task[] tasks = new Task[totalRecords]; for (int i = 0; i < totalRecords; ++i) { barrier.AddParticipant(); int j = i; tasks[j] = Task.Factory.StartNew(() => { GetDataAndStoreData(j); }); } Task.WaitAll(tasks); Console.WriteLine("Backup completed"); Console.ReadLine(); }
public void WyscigStart() { for (int i = 0; i < konie.Length; i++) { lock (bariera) { bariera.AddParticipant(); } konie[i] = new Kon("Kon " + (i + 1), dlugosc); Thread t = new Thread(konie[i].Bieg); t.Start(); } bariera.SignalAndWait(); pozycja.Sort((kon1, kon2) => { return(kon1.czas.CompareTo(kon2.czas)); }); Wypisz(); }
private static bool RunBarrierTest7_Bug603035() { TestHarness.TestLog("*RunBarrierTest7_Bug603035"); bool failed = false; for (int j = 0; j < 100 && !failed; j++) { Barrier b = new Barrier(0); Action[] actions = Enumerable.Repeat((Action)(() => { for (int i = 0; i < 400; i++) { try { b.AddParticipant(); b.RemoveParticipant(); } catch { failed = true; break; } } }), 4).ToArray(); Parallel.Invoke(actions); if (b.ParticipantCount != 0) { failed = true; } } if (failed) { TestHarness.TestLog("Bug603035 failed"); return(false); } TestHarness.TestLog("Bug603035 succeeded"); return(true); }
private static void BarrierDemo() { int totalRecords = GetNumberOfRecords(); Task[] tasks = new Task[totalRecords]; for (int i = 0; i < totalRecords; i++) { Barrier.AddParticipant(); int j = i; tasks[j] = Task.Factory.StartNew(() => { GetDataAndStoreData(j); }); } Task.WaitAll(tasks); Console.WriteLine("Backup has completed."); }
/// <summary> /// Download training preview images for the treatment screen /// </summary> public void DownloadTreatment() { //crearte dir for user (if not already created) //string newDir = CreateDir(dir, _patient.AccountId.ToString()); //newDir = CreateDir(newDir, _patient.PatientTreatment.TreatmentNumber.ToString()); string newDir = CreateDir(dir, "treatmentThumb"); //initilaize the barrier int size = _patient.PatientTreatment.TrainingList.Count; //Barrier _barrier = new Barrier(size + 1); Barrier _barrier = new Barrier(1); for (int i = 0; i < size; i++) { int temp = i; string _from = _patient.PatientTreatment.TrainingList[temp].TrainingThumbs; string _to = newDir + "\\" + _patient.PatientTreatment.TrainingList[temp].TrainingId + ".png"; _patient.PatientTreatment.TrainingList[temp].TrainingThumbs = _to; if (!File.Exists(_to)) { _barrier.AddParticipant(); Task tempThread = new Task(() => { DownloadFile(_from, _to); _barrier.SignalAndWait(); }); tempThread.Start(); } } _barrier.SignalAndWait(); _barrier.Dispose(); }
/// <summary> /// Synchronizes the given programs with the programs that are already attached to this context. /// This can be called while the other programs are running, but will wait until they can get into /// their synchronizable states before executing the synchronization. If no programs are already attached, /// then this method attaches the given program(s) to this context and starts them. /// </summary> public void Sync(IEnumerable <ZoneProgram> zonePrograms, bool forceStop = false, IEnumerable <ISV> isvs = null, dynamic startingParameters = null) { var incomingZonePrograms = zonePrograms as IList <ZoneProgram> ?? zonePrograms.ToList(); var isvsListed = isvs?.ToList(); if (isvsListed != null && isvsListed.Count() != 1 && isvsListed.Count() != incomingZonePrograms.Count()) { throw new Exception("Number of items in isvs should be either 1 or equal to number of zone programs."); } //stop programs if specified to do so if (forceStop) { incomingZonePrograms.ToList().ForEach(zoneProgram => { if (zoneProgram.State == ProgramState.Started) { zoneProgram.Stop(true); } }); } else { incomingZonePrograms.ToList().ForEach(zoneProgram => { if (zoneProgram.State == ProgramState.Started) { zoneProgram.Stop(); } }); } ////incoming program must be stopped if forceStop is not true //if (incomingZonePrograms.Any(zp => zp.State != ProgramState.Stopped)) // throw new Exception("Given program must be stopped before a live sync is executed."); if (incomingZonePrograms.All(zp => zp is ReactiveZoneProgram)) { incomingZonePrograms.ToList().ForEach(zoneProgram => { lock (Barrier) { Barrier.AddParticipant(); //add participant for each program } lock (ZonePrograms) { ZonePrograms.Add(zoneProgram); } }); } else if (incomingZonePrograms.All(zp => zp is LoopingZoneProgram) && ZonePrograms.All(zp => zp is LoopingZoneProgram)) { lock (SyncLock) { //request sync-state from existing programs and incoming programs ZonePrograms.Cast <LoopingZoneProgram>().ToList().ForEach(zp => { zp.RequestSyncState(); }); incomingZonePrograms.Cast <LoopingZoneProgram>().ToList().ForEach(zp => { zp.RequestSyncState(); }); //start all incoming programs for (int i = 0; i < incomingZonePrograms.Count; i++) { var zoneProgram = incomingZonePrograms[i]; zoneProgram.SetSyncContext(this); ZonePrograms.Add(zoneProgram); zoneProgram.Start(sync: false, isv: isvsListed?.Count() == incomingZonePrograms.Count() ? isvsListed.ElementAt(i) : isvsListed?.First(), startingParameters: startingParameters); } //wait for sync-state from all programs (incoming and existing) ZonePrograms.Cast <LoopingZoneProgram>().ToList().ForEach(zp => { zp.IsSynchronizable.WaitForFire(); }); //sync all incoming programs incomingZonePrograms.ToList().ForEach(zoneProgram => { Barrier.AddParticipant(); }); ResetBarrier(); //release all programs from sync-state ZonePrograms.Cast <LoopingZoneProgram>().ToList().ForEach(zp => { zp.WaitForSync.Fire(null, null); }); ////wait until all programs have left sync-state //ZonePrograms.Cast<LoopingZoneProgram>().ToList().ForEach(zp => //{ // zp.LeftSyncTrigger.WaitForFire(); //}); } SyncFinished.Fire(this, null); } else { throw new Exception( "All programs must be of the same type and must be included in the if statement that precedes this exception."); } }
public void Concurrent_CreateDispose_DoesNotThrow(string drmName) { Assert.DoesNotThrowAsync(async() => { using (var goDispose = new Barrier(0)) { var id = 0; async Task DoWork(string drm) { var drmInitData = CreateDrmInitData(drm); var configuration = CreateDrmDescription(drm); var myId = Interlocked.Increment(ref id); var signaled = false; try { Logger.Info($"Creating {drm} Session {myId}"); using (var ses = CencSession.Create(drmInitData, configuration)) { Logger.Info($"Initializing {drm} Session {myId}"); ses.Initialize(); // Widevine cases - 15 concurrent sessions - individual session may take 60s+ // to initialize when run @15 sessions. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(90))) { try { await ses.WaitForInitialization(cts.Token); } catch (OperationCanceledException) { Logger.Info($"TIMEOUT {drm} Session {myId}"); throw; } catch (Exception e) { Logger.Error(e); throw; } } Logger.Info($"{drm} Session {myId} Initialized. Waiting for Dispose"); goDispose.SignalAndWait(); signaled = true; } Logger.Info($"{drm} Session {myId} completed"); } finally { if (!signaled) { goDispose.RemoveParticipant(); } } } var workPool = new List <Task>(); for (var i = 0; i < ConcurrentDrmSessionsLimit; i++) { workPool.Add(DoWork(drmName)); goDispose.AddParticipant(); } await Task.WhenAll(workPool.ToArray()); Logger.Info($"{drmName} Test completed"); } }); }
public static void RunBarrierTest7a() { bool failed = false; for (int j = 0; j < 100 && !failed; j++) { Barrier b = new Barrier(0); Action[] actions = new Action[4]; for (int k = 0; k < 4; k++) { actions[k] = (Action)(() => { for (int i = 0; i < 400; i++) { try { b.AddParticipant(); b.RemoveParticipant(); } catch { failed = true; break; } } }); } Task[] tasks = new Task[actions.Length]; for (int k = 0; k < tasks.Length; k++) tasks[k] = Task.Factory.StartNew((index) => actions[(int)index](), k, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); Task.WaitAll(tasks); if (b.ParticipantCount != 0) failed = true; } if (failed) { Assert.True(false, string.Format("BarrierTests: RunBarrierTest7a failed")); } }
public static void TooManyParticipants() { Barrier b = new Barrier(Int16.MaxValue); Assert.Throws <InvalidOperationException>(() => b.AddParticipant()); }
public static void TooManyParticipants() { Barrier b = new Barrier(Int16.MaxValue); Assert.Throws<InvalidOperationException>(() => b.AddParticipant()); }
public static void RunBarrierTest7a() { for (int j = 0; j < 100; j++) { Barrier b = new Barrier(0); Action[] actions = new Action[4]; for (int k = 0; k < 4; k++) { actions[k] = (Action)(() => { for (int i = 0; i < 400; i++) { b.AddParticipant(); b.RemoveParticipant(); } }); } Task[] tasks = new Task[actions.Length]; for (int k = 0; k < tasks.Length; k++) tasks[k] = Task.Factory.StartNew((index) => actions[(int)index](), k, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); Task.WaitAll(tasks); Assert.Equal(0, b.ParticipantCount); } }