Facebook
From MaxF, 5 Years ago, written in C++.
This paste is a reply to Find all errors from Dmytro Ovdiienko - view diff
Embed
Download Paste or View Raw
Hits: 363
  1. /// Find all errors
  2.  
  3. #include <windows.h>
  4. #include <process.h>
  5.  
  6. /// Critical section guard
  7. /// Closes critical section at the end of the visibility scope
  8. class CSGuard
  9. {
  10. private:
  11.     /// Controled critical section
  12.     CRITICAL_SECTION* cs_;
  13.  
  14. public:
  15.     /// Constructor
  16.     /// Locks critical section
  17.     CSGuard( CRITICAL_SECTION* cs )
  18.         : cs_( cs )
  19.     {
  20.         EnterCriticalSection( cs_ );
  21.     }
  22.  
  23.     /// Destructor
  24.     /// Unlocks critical section
  25.     ~CSGuard()
  26.     {
  27.         LeaveCriticalSection( cs_ );
  28.     }
  29. };
  30.  
  31. /// Performs some background work
  32. class SomeClass
  33. {
  34. private:
  35.     /// Critical section
  36.     CRITICAL_SECTION cs_;
  37.  
  38.     /// Thread descriptor
  39.     HANDLE thread_;
  40.  
  41.     /// Stop falg
  42.     volatile bool exit_;
  43.  
  44.  
  45. public:
  46.     /// Constructor
  47.     SomeClass()
  48.         : thread_( NULL )
  49.     {
  50.         InitializeCriticalSection( &cs_ );
  51.         thread_ = reinterpret_cast<HANDLE>( _beginthread( &thread_func, 0, this ) );
  52.     }
  53.  
  54.     /// Destructor
  55.     ~SomeClass()
  56.     {
  57.         stop();
  58.         DeleteCriticalSection( &cs_ );
  59.     }
  60.  
  61. private:
  62.  
  63.     /// Stops background task and wait until task is terminated
  64.     void stop()
  65.     {
  66.         CSGuard g( &cs_ );
  67.         exit_ = true;
  68.         WaitForSingleObject( thread_, INFINITE );
  69.     }
  70.  
  71.     /// Background task
  72.     static void thread_func( void* args )
  73.     {
  74.         SomeClass* p_this = reinterpret_cast< SomeClass* >( args );
  75.        
  76.         for( ;; ) // infinite loop
  77.         {
  78.             {
  79.                 CSGuard g( &p_this->cs_ );
  80.                 if( p_this->exit_ )
  81.                     break;
  82.             }
  83.  
  84.             Sleep( 100 ); // do some work
  85.         }
  86.     }
  87. };
  88.  
  89.  
  90. /// Test
  91. int main()
  92. {
  93.     SomeClass sc;
  94.     return 0;
  95. }
  96.  
  97.