Processes and threads

To understand the singleton pattern, we need to provide a little context. In the .Net Framework, an application will be composed of lightweight, managed subprocesses called application domains that can comprise one or more managed threads. For the purpose of understanding the singleton pattern, let's define this as a multithreaded application that contains one or more threads running simultaneously. Technically, the threads are actually not running simultaneously, but this is achieved by dividing the available processor time between the threads, so that each thread will execute for a small amount of time and then the thread will suspend activity, allowing for another thread to execute.

Going back to the singleton pattern, in a multithreaded application, special care needs to be taken to ensure that access to the singleton is limited so that only one thread enters specific areas of logic at a time. Because of this synchronization of threads, it is possible for one thread to retrieve a value and update it, and, before it can be stored, another thread also updates the value.

The potential for more than one thread to access the same shared data and update it with unpredictable results can be referred to as a race condition. 

To avoid data being updated incorrectly, some restriction is required to prevent more than one thread from executing the same block of logic at the same time. There are several mechanisms supported in the .Net Framework and, in the singleton pattern, the lock keyword is used. In the following code, the lock keyword is illustrated to show that only one thread at a time can execute the highlighted code while all other threads will be blocked:

public class Inventory
{
int _quantity;
private Object _lock = new Object();

public void RemoveQuantity(int amount)
{
lock (_lock)
{
if (_quantity - amount < 0)
{
throw new Exception("Cannot remove more than we have!");
}
_quantity -= amount;
}
}
}

The lock is a simple way of restricting access to a section of code and can be applied to both object instances, as our previous example shows, and to the sections of code marked as static. 

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

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