How to use Wait method of Microsoft.Coyote.Rewriting.Types.Threading.Monitor class

Best Coyote code snippet using Microsoft.Coyote.Rewriting.Types.Threading.Monitor.Wait

Monitor.cs

Source:Monitor.cs Github

copy

Full Screen

...227 }228 /// <summary>229 /// Releases the lock on an object and blocks the current thread until it reacquires the lock.230 /// </summary>231 public static bool Wait(object obj)232 {233 var runtime = CoyoteRuntime.Current;234 if (runtime.SchedulingPolicy is SchedulingPolicy.Interleaving)235 {236 var block = SynchronizedBlock.Find(obj) ??237 throw new SystemThreading.SynchronizationLockException();238 return block.Wait();239 }240 return SystemThreading.Monitor.Wait(obj);241 }242 /// <summary>243 /// Releases the lock on an object and blocks the current thread until it reacquires the lock.244 /// If the specified time-out interval elapses, the thread enters the ready queue.245 /// </summary>246 public static bool Wait(object obj, int millisecondsTimeout)247 {248 var runtime = CoyoteRuntime.Current;249 if (runtime.SchedulingPolicy is SchedulingPolicy.Interleaving)250 {251 var block = SynchronizedBlock.Find(obj) ??252 throw new SystemThreading.SynchronizationLockException();253 return block.Wait(millisecondsTimeout);254 }255 return SystemThreading.Monitor.Wait(obj, millisecondsTimeout);256 }257 /// <summary>258 /// Releases the lock on an object and blocks the current thread until it reacquires the lock. If the259 /// specified time-out interval elapses, the thread enters the ready queue. This method also specifies260 /// whether the synchronization domain for the context (if in a synchronized context) is exited before261 /// the wait and reacquired afterward.262 /// </summary>263 public static bool Wait(object obj, int millisecondsTimeout, bool exitContext)264 {265 var runtime = CoyoteRuntime.Current;266 if (runtime.SchedulingPolicy is SchedulingPolicy.Interleaving)267 {268 var block = SynchronizedBlock.Find(obj) ??269 throw new SystemThreading.SynchronizationLockException();270 // TODO: implement exitContext.271 return block.Wait(millisecondsTimeout);272 }273 return SystemThreading.Monitor.Wait(obj, millisecondsTimeout, exitContext);274 }275 /// <summary>276 /// Releases the lock on an object and blocks the current thread until it reacquires the lock.277 /// If the specified time-out interval elapses, the thread enters the ready queue.278 /// </summary>279 public static bool Wait(object obj, TimeSpan timeout)280 {281 var runtime = CoyoteRuntime.Current;282 if (runtime.SchedulingPolicy is SchedulingPolicy.Interleaving)283 {284 var block = SynchronizedBlock.Find(obj) ??285 throw new SystemThreading.SynchronizationLockException();286 return block.Wait(timeout);287 }288 return SystemThreading.Monitor.Wait(obj, timeout);289 }290 /// <summary>291 /// Releases the lock on an object and blocks the current thread until it reacquires the lock.292 /// If the specified time-out interval elapses, the thread enters the ready queue. Optionally293 /// exits the synchronization domain for the synchronized context before the wait and reacquires294 /// the domain afterward.295 /// </summary>296 public static bool Wait(object obj, TimeSpan timeout, bool exitContext)297 {298 var runtime = CoyoteRuntime.Current;299 if (runtime.SchedulingPolicy is SchedulingPolicy.Interleaving)300 {301 var block = SynchronizedBlock.Find(obj) ??302 throw new SystemThreading.SynchronizationLockException();303 // TODO: implement exitContext.304 return block.Wait(timeout);305 }306 return SystemThreading.Monitor.Wait(obj, timeout, exitContext);307 }308 /// <summary>309 /// Provides a mechanism that synchronizes access to objects.310 /// </summary>311 internal class SynchronizedBlock : IDisposable312 {313 /// <summary>314 /// Cache from synchronized objects to synchronized block instances.315 /// </summary>316 private static readonly ConcurrentDictionary<object, Lazy<SynchronizedBlock>> Cache =317 new ConcurrentDictionary<object, Lazy<SynchronizedBlock>>();318 /// <summary>319 /// The object used for synchronization.320 /// </summary>321 protected readonly object SyncObject;322 /// <summary>323 /// True if the lock was taken, else false.324 /// </summary>325 internal bool IsLockTaken;326 /// <summary>327 /// The resource associated with this synchronization object.328 /// </summary>329 private readonly Resource Resource;330 /// <summary>331 /// The current owner of this synchronization object.332 /// </summary>333 private ControlledOperation Owner;334 /// <summary>335 /// Wait queue of asynchronous operations.336 /// </summary>337 private readonly List<ControlledOperation> WaitQueue;338 /// <summary>339 /// Ready queue of asynchronous operations.340 /// </summary>341 private readonly List<ControlledOperation> ReadyQueue;342 /// <summary>343 /// Queue of nondeterministically buffered pulse operations to be performed after releasing344 /// the lock. This allows modeling delayed pulse operations by the operation system.345 /// </summary>346 private readonly Queue<PulseOperation> PulseQueue;347 /// <summary>348 /// The number of times that the lock has been acquired per owner. The lock can only349 /// be acquired more than one times by the same owner. A count > 1 indicates that the350 /// invocation by the current owner is reentrant.351 /// </summary>352 private readonly Dictionary<ControlledOperation, int> LockCountMap;353 /// <summary>354 /// Used to reference count accesses to this synchronized block355 /// so that it can be removed from the cache.356 /// </summary>357 private int UseCount;358 /// <summary>359 /// Initializes a new instance of the <see cref="SynchronizedBlock"/> class.360 /// </summary>361 private SynchronizedBlock(object syncObject)362 {363 if (syncObject is null)364 {365 throw new ArgumentNullException(nameof(syncObject));366 }367 this.SyncObject = syncObject;368 this.Resource = new Resource();369 this.WaitQueue = new List<ControlledOperation>();370 this.ReadyQueue = new List<ControlledOperation>();371 this.PulseQueue = new Queue<PulseOperation>();372 this.LockCountMap = new Dictionary<ControlledOperation, int>();373 this.UseCount = 0;374 }375 /// <summary>376 /// Creates a new <see cref="SynchronizedBlock"/> for synchronizing access377 /// to the specified object and enters the lock.378 /// </summary>379 internal static SynchronizedBlock Lock(object syncObject) =>380 Cache.GetOrAdd(syncObject, key => new Lazy<SynchronizedBlock>(381 () => new SynchronizedBlock(key))).Value.EnterLock();382 /// <summary>383 /// Finds the synchronized block associated with the specified synchronization object.384 /// </summary>385 internal static SynchronizedBlock Find(object syncObject) =>386 Cache.TryGetValue(syncObject, out Lazy<SynchronizedBlock> lazyMock) ? lazyMock.Value : null;387 /// <summary>388 /// Determines whether the current thread holds the lock on the sync object.389 /// </summary>390 internal bool IsEntered()391 {392 if (this.Owner != null)393 {394 var op = this.Resource.Runtime.GetExecutingOperation();395 return this.Owner == op;396 }397 return false;398 }399 private SynchronizedBlock EnterLock()400 {401 this.IsLockTaken = true;402 SystemInterlocked.Increment(ref this.UseCount);403 if (this.Owner is null)404 {405 // If this operation is trying to acquire this lock while it is free, then inject a scheduling406 // point to give another enabled operation the chance to race and acquire this lock.407 this.Resource.Runtime.ScheduleNextOperation(default, SchedulingPointType.Acquire);408 }409 if (this.Owner != null)410 {411 var op = this.Resource.Runtime.GetExecutingOperation();412 if (this.Owner == op)413 {414 // The owner is re-entering the lock.415 this.LockCountMap[op]++;416 return this;417 }418 else419 {420 // Another op has the lock right now, so add the executing op421 // to the ready queue and block it.422 this.WaitQueue.Remove(op);423 if (!this.ReadyQueue.Contains(op))424 {425 this.ReadyQueue.Add(op);426 }427 this.Resource.Wait();428 this.LockCountMap.Add(op, 1);429 return this;430 }431 }432 // The executing op acquired the lock and can proceed.433 this.Owner = this.Resource.Runtime.GetExecutingOperation();434 this.LockCountMap.Add(this.Owner, 1);435 return this;436 }437 /// <summary>438 /// Notifies a thread in the waiting queue of a change in the locked object's state.439 /// </summary>440 internal void Pulse() => this.SchedulePulse(PulseOperation.Next);441 /// <summary>442 /// Notifies all waiting threads of a change in the object's state.443 /// </summary>444 internal void PulseAll() => this.SchedulePulse(PulseOperation.All);445 /// <summary>446 /// Schedules a pulse operation that will either execute immediately or be scheduled447 /// to execute after the current owner releases the lock. This nondeterministic action448 /// is controlled by the runtime to simulate scenarios where the pulse is delayed by449 /// the operation system.450 /// </summary>451 private void SchedulePulse(PulseOperation pulseOperation)452 {453 var op = this.Resource.Runtime.GetExecutingOperation();454 if (this.Owner != op)455 {456 throw new SystemSynchronizationLockException();457 }458 // Pulse has a delay in the operating system, we can simulate that here459 // by scheduling the pulse operation to be executed nondeterministically.460 this.PulseQueue.Enqueue(pulseOperation);461 if (this.PulseQueue.Count is 1)462 {463 // Create a task for draining the queue. To optimize the testing performance,464 // we create and maintain a single task to perform this role.465 Task.Run(this.DrainPulseQueue);466 }467 }468 /// <summary>469 /// Drains the pulse queue, if it contains one or more buffered pulse operations.470 /// </summary>471 private void DrainPulseQueue()472 {473 while (this.PulseQueue.Count > 0)474 {475 // Pulses can happen nondeterministically while other operations execute,476 // which models delays by the OS.477 this.Resource.Runtime.ScheduleNextOperation(default, SchedulingPointType.Default);478 var pulseOperation = this.PulseQueue.Dequeue();479 this.Pulse(pulseOperation);480 if (this.Owner is null)481 {482 this.UnlockNextReady();483 }484 }485 }486 /// <summary>487 /// Invokes the pulse operation.488 /// </summary>489 private void Pulse(PulseOperation pulseOperation)490 {491 if (pulseOperation is PulseOperation.Next)492 {493 if (this.WaitQueue.Count > 0)494 {495 // System.Threading.Monitor has FIFO semantics.496 var waitingOp = this.WaitQueue[0];497 this.WaitQueue.RemoveAt(0);498 this.ReadyQueue.Add(waitingOp);499 IO.Debug.WriteLine("[coyote::debug] Operation '{0}' is pulsed by task '{1}'.",500 waitingOp.Id, SystemTask.CurrentId);501 }502 }503 else504 {505 foreach (var waitingOp in this.WaitQueue)506 {507 this.ReadyQueue.Add(waitingOp);508 IO.Debug.WriteLine("[coyote::debug] Operation '{0}' is pulsed by task '{1}'.",509 waitingOp.Id, SystemTask.CurrentId);510 }511 this.WaitQueue.Clear();512 }513 }514 /// <summary>515 /// Releases the lock on an object and blocks the current thread until it reacquires516 /// the lock.517 /// </summary>518 internal bool Wait()519 {520 var op = this.Resource.Runtime.GetExecutingOperation();521 if (this.Owner != op)522 {523 throw new SystemSynchronizationLockException();524 }525 this.ReadyQueue.Remove(op);526 if (!this.WaitQueue.Contains(op))527 {528 this.WaitQueue.Add(op);529 }530 this.UnlockNextReady();531 IO.Debug.WriteLine("[coyote::debug] Operation '{0}' with task id '{1}' is waiting.",532 op.Id, SystemTask.CurrentId);533 // Block this operation and schedule the next enabled operation.534 this.Resource.Wait();535 return true;536 }537 /// <summary>538 /// Releases the lock on an object and blocks the current thread until it reacquires539 /// the lock. If the specified time-out interval elapses, the thread enters the ready540 /// queue.541 /// </summary>542#pragma warning disable CA1801 // Parameter not used543 internal bool Wait(int millisecondsTimeout)544 {545 // TODO: how to implement timeout?546 // This is a bit more tricky to model, one way is to have a loop that checks547 // for controlled random boolean choice, and if it becomes true then it fails548 // the wait. This would be similar to timers in actors, so we want to use a549 // lower probability to not fail very frequently during systematic testing.550 // In the future we might want to introduce a RandomTimeout choice (similar to551 // RandomBoolean and RandomInteger), with the benefit being that the underlying552 // testing strategy will know that this is a timeout and perhaps treat it in a553 // more intelligent manner, but for now piggybacking on the other randoms should554 // work (as long as its not with a high probability).555 return this.Wait();556 }557#pragma warning restore CA1801 // Parameter not used558 /// <summary>559 /// Releases the lock on an object and blocks the current thread until it reacquires560 /// the lock. If the specified time-out interval elapses, the thread enters the ready561 /// queue.562 /// </summary>563#pragma warning disable CA1801 // Parameter not used564 internal bool Wait(TimeSpan timeout)565 {566 // TODO: how to implement timeout?567 return this.Wait();568 }569#pragma warning restore CA1801 // Parameter not used570 /// <summary>571 /// Assigns the lock to the next operation waiting in the ready queue, if there is one,572 /// following the FIFO semantics of monitor.573 /// </summary>574 private void UnlockNextReady()575 {576 // Preparing to unlock so give up ownership.577 this.Owner = null;578 if (this.ReadyQueue.Count > 0)579 {580 // If there is a operation waiting in the ready queue, then signal it.581 ControlledOperation op = this.ReadyQueue[0];...

Full Screen

Full Screen

RewritingEngine.cs

Source:RewritingEngine.cs Github

copy

Full Screen

...279 }280 if (this.Options.IsReplacingAssemblies)281 {282 string targetPath = Path.Combine(this.Options.AssembliesDirectory, assemblyName);283 this.CopyWithRetriesAsync(outputPath, assemblyPath).Wait();284 if (readParams.ReadSymbols)285 {286 string pdbFile = Path.ChangeExtension(outputPath, "pdb");287 string targetPdbFile = Path.ChangeExtension(targetPath, "pdb");288 this.CopyWithRetriesAsync(pdbFile, targetPdbFile).Wait();289 }290 }291 }292 private async Task CopyWithRetriesAsync(string srcFile, string targetFile)293 {294 for (int retries = 10; retries >= 0; retries--)295 {296 try297 {298 File.Copy(srcFile, targetFile, true);299 }300 catch (Exception)301 {302 if (retries is 0)...

Full Screen

Full Screen

MonitorTests.cs

Source:MonitorTests.cs Github

copy

Full Screen

...23 {24 this.Test(async () =>25 {26 SignalData signal = new SignalData();27 var t1 = Task.Run(signal.Wait);28 var t2 = Task.Run(signal.Signal);29 await Task.WhenAll(t1, t2);30 },31 this.GetConfiguration().WithTestingIterations(100));32 }33 [Fact(Timeout = 5000)]34 public void TestMonitorWithReentrancy1()35 {36 this.Test(() =>37 {38 SignalData signal = new SignalData();39 signal.ReentrantLock();40 },41 this.GetConfiguration().WithTestingIterations(100));42 }43 [Fact(Timeout = 5000)]44 public void TestMonitorWithReentrancy2()45 {46 this.Test(async () =>47 {48 SignalData signal = new SignalData();49 Task t1 = Task.Run(signal.ReentrantLock);50 Task t2 = Task.Run(signal.DoLock);51 await Task.WhenAll(t1, t2);52 },53 this.GetConfiguration().WithTestingIterations(100));54 }55 [Fact(Timeout = 5000)]56 public void TestMonitorWithReentrancy3()57 {58 this.Test(async () =>59 {60 SignalData signal = new SignalData();61 Task t1 = Task.Run(signal.ReentrantWait);62 Task t2 = Task.Run(signal.Signal);63 await Task.WhenAll(t1, t2);64 },65 this.GetConfiguration().WithTestingIterations(100));66 }67 [Fact(Timeout = 5000)]68 public void TestMonitorWithInvalidSyncObject()69 {70 this.TestWithException<ArgumentNullException>(() =>71 {72 using var monitor = SynchronizedBlock.Lock(null);73 },74 replay: true);75 }76 [Fact(Timeout = 5000)]77 public void TestMonitorWithInvalidWaitState()78 {79 this.TestWithException<SynchronizationLockException>(() =>80 {81 SynchronizedBlock monitor;82 using (monitor = SynchronizedBlock.Lock(new object()))83 {84 }85 monitor.Wait();86 },87 replay: true);88 }89 [Fact(Timeout = 5000)]90 public void TestMonitorWithInvalidPulseState()91 {92 this.TestWithException<SynchronizationLockException>(() =>93 {94 SynchronizedBlock monitor;95 using (monitor = SynchronizedBlock.Lock(new object()))96 {97 }98 monitor.Pulse();99 },100 replay: true);101 }102 [Fact(Timeout = 5000)]103 public void TestMonitorWithInvalidPulseAllState()104 {105 this.TestWithException<SynchronizationLockException>(() =>106 {107 SynchronizedBlock monitor;108 using (monitor = SynchronizedBlock.Lock(new object()))109 {110 }111 monitor.PulseAll();112 },113 replay: true);114 }115 [Fact(Timeout = 5000)]116 public void TestMonitorWithInvalidUsage()117 {118 this.TestWithError(async () =>119 {120 try121 {122 var monitor = SynchronizedBlock.Lock(new object());123 // We yield to make sure the execution is asynchronous.124 await Task.Yield();125 monitor.Pulse();126 // We do not dispose inside a using statement, because the `SynchronizationLockException`127 // will trigger the disposal, which will fail because an await statement is not allowed128 // inside a synchronized block. The C# compiler normally prevents it when using the lock129 // statement, but we cannot prevent it when directly using the mock.130 monitor.Dispose();131 }132 catch (SynchronizationLockException)133 {134 Specification.Assert(false, "Expected exception thrown.");135 }136 },137 expectedError: "Expected exception thrown.",138 replay: true);139 }140 [Fact(Timeout = 5000)]141 public void TestComplexMonitor()142 {143 this.Test(async () =>144 {145 object syncObject = new object();146 bool waiting = false;147 List<string> log = new List<string>();148 Task t1 = Task.Run(() =>149 {150 Monitor.Enter(syncObject);151 log.Add("waiting");152 waiting = true;153 Monitor.Wait(syncObject);154 log.Add("received pulse");155 Monitor.Exit(syncObject);156 });157 Task t2 = Task.Run(async () =>158 {159 while (!waiting)160 {161 await Task.Delay(1);162 }163 Monitor.Enter(syncObject);164 Monitor.Pulse(syncObject);165 log.Add("pulsed");166 Monitor.Exit(syncObject);167 });168 await Task.WhenAll(t1, t2);169 string expected = "waiting, pulsed, received pulse";170 string actual = string.Join(", ", log);171 Specification.Assert(expected == actual, "ControlledMonitor out of order, '{0}' instead of '{1}'", actual, expected);172 },173 this.GetConfiguration());174 }175 private class SignalData176 {177 private readonly object SyncObject;178 internal bool Signalled;179 internal SignalData()180 {181 this.SyncObject = new object();182 this.Signalled = false;183 }184 internal void Signal()185 {186 using var monitor = SynchronizedBlock.Lock(this.SyncObject);187 this.Signalled = true;188 monitor.Pulse();189 }190 internal void Wait()191 {192 using var monitor = SynchronizedBlock.Lock(this.SyncObject);193 while (!this.Signalled)194 {195 bool result = monitor.Wait();196 Assert.True(result, "Wait returned false.");197 }198 }199 internal void ReentrantLock()200 {201 Debug.WriteLine("Entering lock on task {0}.", GetCurrentTaskId());202 using var monitor = SynchronizedBlock.Lock(this.SyncObject);203 Debug.WriteLine("Entered lock on task {0}.", GetCurrentTaskId());204 this.DoLock();205 }206 internal void DoLock()207 {208 using var monitor = SynchronizedBlock.Lock(this.SyncObject);209 Debug.WriteLine("Re-entered lock from the same task {0}.", GetCurrentTaskId());210 }211 internal void ReentrantWait()212 {213 Debug.WriteLine("Entering lock on task {0}.", GetCurrentTaskId());214 using var monitor = SynchronizedBlock.Lock(this.SyncObject);215 Debug.WriteLine("Entered lock on task {0}.", GetCurrentTaskId());216 this.DoWait();217 }218 internal void DoWait()219 {220 using var monitor = SynchronizedBlock.Lock(this.SyncObject);221 Debug.WriteLine("Re-entered lock from the same task {0}.", GetCurrentTaskId());222 Debug.WriteLine("Task {0} is now waiting...", GetCurrentTaskId());223 this.Wait();224 Debug.WriteLine("Task {0} received the signal.", GetCurrentTaskId());225 }226 internal static int GetCurrentTaskId() => Task.CurrentId ?? 0;227 }228 }229}...

Full Screen

Full Screen

Wait

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting.Types.Threading;2{3 public static void Main()4 {5 object o = new object();6 Monitor.Enter(o);7 Monitor.Wait(o);8 Monitor.Exit(o);9 }10}11using System.Threading;12{13 public static void Main()14 {15 object o = new object();16 Monitor.Enter(o);17 Monitor.Wait(o);18 Monitor.Exit(o);19 }20}211.cs(7,9): error CS0117: 'Monitor' does not contain a definition for 'Wait'22using Microsoft.Coyote.Rewriting.Types.Threading;23{24 public static void Main()25 {26 object o = new object();27 Monitor m = new Monitor(o);28 m.Enter();29 m.Wait();30 m.Exit();31 }32}33using Microsoft.Coyote.Rewriting.Types.Threading;34{35 public static void Main()36 {37 object o = new object();38 Monitor m = new Monitor(o);39 m.Enter();40 m.Wait();41 m.Exit();42 }43}

Full Screen

Full Screen

Wait

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote.Rewriting.Types.Threading;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 Monitor.Enter("lock");9 Monitor.Wait("lock");10 Console.WriteLine("Hello World!");11 Monitor.Exit("lock");12 }13 }14}15using System;16using System.Threading;17using System.Threading.Tasks;18{19 {20 static void Main(string[] args)21 {22 Monitor.Enter("lock");23 Monitor.Wait("lock");24 Console.WriteLine("Hello World!");25 Monitor.Exit("lock");26 }27 }28}29.locals init (object V_0)30IL_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)31IL_000d: call void Microsoft.Coyote.Rewriting.Types.Threading.Monitor::Wait(object)32IL_0017: call void [mscorlib]System.Console::WriteLine(string)33IL_001d: call void [mscorlib]System.Threading.Monitor::Exit(object)34.locals init (object V_0)35IL_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)36IL_000d: call void [mscorlib]System.Threading.Monitor::Wait(object)

Full Screen

Full Screen

Wait

Using AI Code Generation

copy

Full Screen

1{2 static void Main(string[] args)3 {4 Program p = new Program();5 p.Run();6 }7 public void Run()8 {9 var t1 = new Thread(() =>10 {11 lock (this)12 {13 Monitor.Wait(this);14 }15 });16 t1.Start();17 var t2 = new Thread(() =>18 {19 lock (this)20 {21 Monitor.Pulse(this);22 }23 });24 t2.Start();25 }26}27{28 static void Main(string[] args)29 {30 Program p = new Program();31 p.Run();32 }33 public void Run()34 {35 var t1 = new Thread(() =>36 {37 lock (this)38 {39 System.Threading.Monitor.Wait(this);40 }41 });42 t1.Start();43 var t2 = new Thread(() =>44 {45 lock (this)46 {47 System.Threading.Monitor.Pulse(this);48 }49 });50 t2.Start();51 }52}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Coyote automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful