balance amount always reflects the amount credited or debited. For example, if the balance is 500, and 100 is credited, the balance should be 600. To ensure that crediting and debiting work correctly, you need to obtain a mutually exclusive lock on the block of code performing the crediting or debiting. A mutually exclusive lock means that once a thread is executing a block of code that is locked, other threads that also want to execute that code block will have to wait.

Figure 10-5

To enable you to create a mutually exclusive lock on a block of code (the code that is locked is called a critical section), C# provides the lock keyword. Using it, you can ensure that a block of code runs to completion without any interruption by other threads.

To lock a block of code, give the lock statement an object as argument. The preceding code could be written as follows:

class Program {

 //---used for locking---

 static object obj = new object();

 //---initial balance amount---

 static int balance = 500;

 static void Main(string[] args) {

  Thread t1 = new Thread(new ThreadStart(Debit));

  t1.Start();

  Thread t2 = new Thread(new ThreadStart(Credit));

  t2.Start();

  Console.ReadLine();

 }

 static void Credit() {

  //---credit 1500---

  for (int i = 0; i < 15; i++) {

   lock (obj) {

    balance += 100;

    Console.WriteLine('After crediting, balance is {0}', balance);

   }

  }

 }

 static void Debit() {

  //---debit 1000---

  for (int i = 0; i < 10; i++) {

   lock (obj) {

    balance -= 100;

    Console.WriteLine('After debiting, balance is {0}', balance);

   }

  }

 }

}

Notice that you first create an instance of an object that will be used for locking purposes:

//---used for locking---

static object obj = new object();

In general, it is best to avoid using a public object for locking purposes. This prevents situations in which threads are all waiting for a public object, which may itself be locked by some other code.

To delineate a block of code to lock, enclose the statements with the lock statement:

lock (obj) {

 //---place code here---

}

As long as one thread is executing the statements within the block, all other threads will have to wait for the statements to be completed before they can execute the statements.

Figure 10-6 shows one possible outcome of the execution.

Figure 10-6

Notice that the value of balance is now consistent after each credit/debit operation.

Monitor Class

The limitation of the lock statement is that you do not have the capability to release the lock halfway through the critical section. This is important because there are situations in which one thread needs to release the lock so that other threads have a chance to proceed before the first thread can resume its execution.

For instance, you saw in Figure 10-6 that on the fifth line the balance goes into a negative value. In real life this might not be acceptable. The bank might not allow your account to go into a negative balance, and thus you need to ensure that you have a positive balance before any more debiting can proceed. Hence, you need to check the value of balance. If it is 0, then you should release the lock and let the crediting thread have a chance to increment the balance before you do any more debiting.

For this purpose, you can use the Monitor class provided by the .NET Framework class library. Monitor is a static class that controls access to objects by providing a lock. Here's a rewrite of the previous program using the Monitor class:

class Program {

 //---used for locking---

 static object obj = new object();

 //---initial balance amount---

 static int balance = 500;

 static void Main(string[] args) {

  Thread t1 = new Thread(new ThreadStart(Debit));

  t1.Start();

  Thread t2 = new Thread(new ThreadStart(Credit));

  t2.Start();

  Console.ReadLine();

 }

 static void Credit() {

  //---credit 1500---

  for (int i = 0; i < 15; i++) {

   Monitor.Enter(obj);

   balance += 100;

   Console.WriteLine('After crediting, balance is {0}', balance);

   Monitor.Exit(obj);

  }

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату