Critical.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "Critical.h"
  2. #include "Globals.h"
  3. #include "Thread.h"
  4. #include <iostream>
  5. #include <time.h>
  6. using namespace Framework;
  7. // Inhalt der Critical class aus Critical.h
  8. // Konstructor
  9. Critical::Critical()
  10. {
  11. InitializeCriticalSection( &cs );
  12. owner = 0;
  13. lockCount = 0;
  14. id = (int)time( 0 );
  15. }
  16. // Destructor
  17. Critical::~Critical()
  18. {
  19. DeleteCriticalSection( &cs );
  20. }
  21. // sperrt das Objekt
  22. void Critical::lock()
  23. {
  24. pthread_t t = GetCurrentThread();
  25. getThreadRegister()->lock();
  26. Thread *tmp = getThreadRegister()->zThread( t );
  27. if( tmp )
  28. tmp->addCriticalLock();
  29. getThreadRegister()->unlock();
  30. EnterCriticalSection( &cs );
  31. if( !owner )
  32. owner = tmp;
  33. lockCount++;
  34. }
  35. // versucht das Objekt zu sperren
  36. bool Critical::tryLock()
  37. {
  38. if( lockCount > 0 )
  39. return false;
  40. getThreadRegister()->lock();
  41. Thread *tmp = getThreadRegister()->zThread( GetCurrentThread() );
  42. if( tmp )
  43. tmp->addCriticalLock();
  44. getThreadRegister()->unlock();
  45. EnterCriticalSection( &cs );
  46. if( !owner )
  47. owner = tmp;
  48. lockCount++;
  49. return true;
  50. }
  51. // entsperrt das Objekt
  52. void Critical::unlock()
  53. {
  54. getThreadRegister()->lock();
  55. Thread *tmp = 0;
  56. if( getThreadRegister()->isThread( owner ) )
  57. {
  58. if( owner && GetThreadId( owner->getThreadHandle() ) != GetThreadId( GetCurrentThread() ) )
  59. throw std::runtime_error( "A Thread that does not own a Critical Object trys to unlock it" );
  60. tmp = owner;
  61. }
  62. getThreadRegister()->unlock();
  63. if( !--lockCount )
  64. owner = 0;
  65. LeaveCriticalSection( &cs );
  66. getThreadRegister()->lock();
  67. if( tmp && getThreadRegister()->isThread( tmp ) )
  68. tmp->removeCriticalLock();
  69. getThreadRegister()->unlock();
  70. }
  71. // gibt true zurück, wenn das Objekt gesperrt ist
  72. bool Critical::isLocked() const
  73. {
  74. return lockCount > 0;
  75. }
  76. // gibt einen Zeiger auf den Thread zurück, der das Objekt gesperrt hat
  77. const Thread *Critical::zOwner() const
  78. {
  79. return owner;
  80. }