Here’s (a simplified version of) what’s actually happening within the Go method of the preceding example: Monitor.Enter and Monitor.ExitĬ#’s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with atry/finally block. In this case, we’re protecting the logic inside the Go method, as well as the fields val1 and val2. Exclusive locks are sometimes said to enforceserialized access to whatever’s protected by the lock, because one thread’s access cannot overlap with that of another. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis (a caveat is that nuances in the behavior of Windows and the CLR mean that the fairness of the queue can sometimes be violated). Only one thread can lock the synchronizing object (in this case, locker) at a time, and any contending threads areblocked until the lock is released. Static readonly object locker = new object() This class is not thread-safe: if Go was called by two threads simultaneously, it would be possible to get a division-by-zero error, because val2 could be set to zero in one thread right as the other thread was in between executing the if statement and Console.WriteLine. Of the two, the lock construct is faster and more convenient.Mutex, though, has a niche in that its lock can span applications in different processes on the computer. The two main exclusive locking constructs are lock and Mutex. Exclusive locking is used to ensure that only one thread can enter particular sections of code at a time.
0 Comments
Leave a Reply. |