Synchronization

With the introduction of Win32 came preemptive multitasking. Preemptive multitasking means that a thread may be interrupted at any time to allow another thread to process. This happens without regard to the state of the thread. This also means that if one thread is trying to write to a variable and another thread is trying to read that same variable, the outcome can be indeterminate. Imagine raising an apple to eat it and at the same time you begin to take a bite, someone else shoves his head in there and takes a bite first. Besides potentially getting an unexpected taste of human hair, the result is that you don't get what you wanted or expected. If you don't employ some sort of synchronization scheme in your multithreaded applications, this is essentially the same problem that can occur. In this section, you will see and use the different synchronization types and the ways that they are implemented in .NET.

Understanding the Different Types of Synchronization

As with everything, there are many ways to accomplish the same task. Each way takes a different approach, and with each approach comes some advantages and disadvantages. The same holds true with the different synchronization schemes. Table 9.3 lists the four basic types of synchronization and the corresponding .NET class that uses each scheme.

Table 9.3. Win32 Basic Synchronization Types
Synchronization TypeDescriptionCorresponding .NET Class(es)
MutexA mutex synchronization prevents more then one thread from accessing a shared resource at a time.Mutex
Critical SectionA critical section synchronization does the same thing as a mutex, but with one exception: It does not work across processes.lock, Monitor, Interlocked, ReaderWriterLock
SemaphoreA semaphore synchronization limits the number of threads that can access the same shared resource.None
EventAn event synchronization can signal other threads to perform specific actions.AutoResetEvent, ManualResetEvent, WaitHandle

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182