home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 7 / 07.iso / c / c100 / 3.ddi / TASK.ZIP / SEM.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1989-08-28  |  1.7 KB  |  67 lines

  1. /*****************************************************
  2. File: SEM.CPP       Copyright 1989 by Dlugosz Software
  3.    Semaphore class from the C++ multitasking system.
  4. *****************************************************/
  5.  
  6. #include "usual.hpp"
  7. #include "task.hpp"
  8. #include "sem.hpp"
  9.  
  10. /* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
  11.  
  12. semaphore::semaphore (unsigned initial_value)
  13. {
  14. value= initial_value;
  15. // task_list is implicitly initialized
  16. }
  17.  
  18. /* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
  19.  
  20. semaphore::semaphore()
  21. {
  22. // this constructor is provided so you can have arrays of semaphores
  23. value= 1;
  24. }
  25.  
  26. /* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
  27.  
  28. bool semaphore::wait()
  29. {
  30. int newval;
  31. // first, decrement the value
  32. {  race_condition_cure _;
  33.    newval= --value;
  34.    }
  35. if (newval < 0) {
  36.    // gotta wait
  37.    active_task->block(blocked);  //put it in my list
  38.    /* ... in limbo ...*/
  39.    //I'm back.  A siginal has caused this task to be resumed, or
  40.    //the task was run as part of shutdown
  41.    if (active_task->iskilled() || active_task->isfaulted()) {  //abnormal
  42.       if (active_task->iskilled()) //fix up semaphore count
  43.          value++;  //I left the blocked list, correct the count
  44.          /* If you're wondering why I can just say value++ without
  45.             worry, It is because the task on the 'kill run' is not
  46.             preemptable. */
  47.       return FALSE;  //abnormal return
  48.       }
  49.    }
  50. return TRUE;
  51. }
  52.  
  53. /* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
  54.  
  55. void semaphore::signal()
  56. {
  57. int newval;
  58. // increment the value
  59. {  race_condition_cure _;
  60.    newval= ++value;
  61.    }
  62. if (newval < 1)  //I just freed up a blocked task
  63.    blocked.resume_one();
  64. }
  65.  
  66. /* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
  67.