Page 324 - DCAP404 _Object Oriented Programming
P. 324

Unit 14: Advanced Concept in C++




          As is evident, the shared variable is checked and updated as an atomic operation so that the race  Notes
          condition does not occur.

          Deadlock

          The concurrency may lead to a situation where one or more threads wait for resources that can
          never become available. Such a condition is called a deadlock. Consider the following code that
          illustrates a deadlock.
                 mutex  X;

                 mutex  Y;
                 void  ThreadThree()
                 {
                         int  ct  =  0;
                         while(true)
                         {
                         mutex::lock(X);

                         mutex::lock(Y);
                         cout  <<  “ThreadThree  in  action”  <<++ct<<  “\n”;
                         }
                 }
                 void  ThreadFour()
                 {
                         int  ct  =  0;
                         while(true)
                         {

                         mutex::lock(Y);
                         mutex::lock(X);
                         cout  <<  “ThreadFour  in  action”  <<  ++ct<<  “\n”;
                         }
                 }
          When this code is run a deadlock is possible. The two threads may enter  a situation where
          ThreadThree is  waiting for  ThreadFour to  release  the  locks while  ThreadFour waits  for
          ThreadThree to release the locks.
          To resolve this simple  deadlock all we need to do is to ensure that we lock  resources in a
          consistent order. Thus, changing ThreadFour to lock X before Y ensures there will be no deadlock.

          Self Assessment

          Fill in the blanks:
          12.  A ……………………….. is a sequence of instructions to be executed within a program.






                                           LOVELY PROFESSIONAL UNIVERSITY                                   317
   319   320   321   322   323   324   325   326   327   328   329