Page 322 - DCAP404 _Object Oriented Programming
P. 322

Unit 14: Advanced Concept in C++




                 From Main Thread: Work Work Work.                                              Notes
                 Thread Procedure: 3
                 From Main Thread: Call Join(), to wait until ThreadProc ends.
                 Thread Procedure: 4

                 From Main Thread: Press Enter to end program.

          Multithreading

          A  single process  can be  further broken  into several  threads so  as to  enhance  the  overall
          performance of the process. This is called multithreading. Hence, multithreading is a technique
          for achieving concurrency within a process.
          Multithreading vs. Multiprocessing


          Multithreading allows an application with multiple threads running within a process. On the
          other hand, multiprocessing refers to an application organized across multiple processes.
          Context  switching and synchronization costs  are comparatively  lower in threads. Since the
          address space is shared among threads no extra work is  required to access them. However,
          because of this the failure of one thread in a process can ring down all the other threads of that
          process. In contrast, since processes are insulated from each other by the operating system, an
          error in one process cannot bring down another process.





             Notes  Processes may run on behalf of different users and therefore may have different
             permissions unlike threads.

          Limitations of Threads

          Despite having so much promises threads do carry a lot of pitfalls along the way. Programmers
          should take proper caution while programming with threads. Some of the caveats of thread
          programming is discussed below.

          Race Conditions

          A race condition is said to exist where the behavior of code depends on  the interleaving of
          multiple threads. Single-threaded codes runs as a single sequence of statements from which we
          can assume that data does not change between statements. However, we cannot make the same
          assumption for a single program statement which may compile into more than one lower level
          statements, i.e., we cannot guarantee the outcome of a statement such as total++; if total is shared
          between multiple threads. This is perhaps the most fundamental problem with multi-threaded
          programming. Consider the following code that depicts a logical race condition.
          int SharedVar = 20;
          void* ThreadOne(void*)
          {
                         while(SharedVar  >  0)
                         {




                                           LOVELY PROFESSIONAL UNIVERSITY                                   315
   317   318   319   320   321   322   323   324   325   326   327