Facebook
From Dmytro Ovdiienko, 5 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 370
  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.     /// Thread descriptor
  36.     HANDLE thread_;
  37.  
  38.     /// Stop falg
  39.     volatile bool exit_;
  40.  
  41.     /// Critical section
  42.     CRITICAL_SECTION cs_;
  43.  
  44. public:
  45.     /// Constructor
  46.     SomeClass()
  47.         : thread_( reinterpret_cast<HANDLE>( _beginthread( &thread_func, 0, this ) ) )
  48.     {
  49.         InitializeCriticalSection( &cs_ );
  50.     }
  51.  
  52.     /// Destructor
  53.     ~SomeClass()
  54.     {
  55.         stop();
  56.         DeleteCriticalSection( &cs_ );
  57.     }
  58.  
  59. private:
  60.  
  61.     /// Stops background task and wait until task is terminated
  62.     void stop()
  63.     {
  64.         CSGuard g( &cs_ );
  65.         exit_ = true;
  66.         WaitForSingleObject( thread_, INFINITE );
  67.     }
  68.  
  69.     /// Background task
  70.     static void thread_func( void* args )
  71.     {
  72.         SomeClass* p_this = reinterpret_cast< SomeClass* >( args );
  73.        
  74.         for( ;; ) // infinite loop
  75.         {
  76.             {
  77.                 CSGuard g( &p_this->cs_ );
  78.                 if( p_this->exit_ )
  79.                     break;
  80.             }
  81.  
  82.             Sleep( 100 ); // do some work
  83.         }
  84.     }
  85. };
  86.  
  87.  
  88. /// Test
  89. int main()
  90. {
  91.     SomeClass sc;
  92.     return 0;
  93. }
  94.  
  95.  

Replies to Find all errors rss

Title Name Language When
Re: Find all errors MaxF cpp 5 Years ago.