Advanced Multi-threading in C#
25.1 INTRODUCTION AND OBJECTIVES
In this chapter we extend the multi-threading concepts developed in Chapter 24. In that chapter we concentrated on describing what multi-threading is and how to write basic multi-threaded code in C#.
We now introduce a number of multi-threaded concepts and their realisation in C#:
- Ensuring that shared data is atomically updated in a multi-threaded environment by using locking mechanisms; avoiding race conditions.
- Specific locking mechanisms: Mutex, Semaphore, Monitor.
- Thread notification and synchronisation.
- Timers and background threads.
- Thread-safe data structures.
We discuss each concept in detail and we give examples of use.
Before we discuss advanced multi-threaded syntax in detail we describe the difference between sequential and parallel execution models. To this end, we discuss how computer programs run (see Downey 2008 for a clear introduction to parallel models and examples). In the sequential model a computer executes statements in sequence. This is because there is only one thread of control and hence there is no contention for resources. In code, if statement a1 comes before statement a2 then a1 will be executed first, for example:
a1 x = 5; a2 print x;
When multiple processors are running at the same time in a computer then it is not clear which processor will execute which statement and in which order. In this case we say that the resulting behaviour is non-deterministic. The same non-deterministic ...