In this chapter, we will cover the following recipes:
SpinLock
for synchronizationReaderWriterLockSlim
WaitHandles
with MutexCountdownEvent
ManualResetEventSlim
to spin and waitSemaphoreSlim
to limit accessThis chapter is about coordinating the work that is performed by parallel tasks.
When concurrent tasks read from and write to variables without an appropriate synchronization mechanism, a race condition has the potential to appear. Race conditions can produce inconsistent results in your program, and can be very difficult to detect and correct.
Let's take a second to understand what a race condition is. Consider a scenario that has two parallel tasks; task1 and task2. Each task tries to read and increment the value of a public variable. Task1 reads the original value of the variable, let's say 10, and increments the value to 11. At the same time task1 is reading the value of the variable but before it increments the value, task2 reads the same value of 10 and increments to 11. The final value of the variable ends up being 11 instead of the correct value of 12.
.NET framework 4.5 offers several new data structures for parallel programming that simplify complex synchronization problems. Knowledge of these synchronization primitives will enable you to implement more complex algorithms and solve many of the issues associated with multithreaded programming. It is important to learn the various alternatives so that you can choose the most appropriate one for scenarios that require communication and synchronization among multiple tasks.
3.133.131.168