#include
#include
/// Critical section guard
/// Closes critical section at the end of the visibility scope
class CSGuard
{
private:
/// Controled critical section
CRITICAL_SECTION* cs_;
public:
/// Constructor
/// Locks critical section
CSGuard( CRITICAL_SECTION* cs )
: cs_( cs )
{
EnterCriticalSection( cs_ );
}
/// Destructor
/// Unlocks critical section
~CSGuard()
{
LeaveCriticalSection( cs_ );
}
};
/// Performs some background work
class SomeClass
{
private:
/// Critical section
CRITICAL_SECTION cs_;
/// Thread descriptor
HANDLE thread_;
/// Stop falg
volatile bool
/// Critical section
CRITICAL_SECTION cs_;
public:
/// Constructor
SomeClass()
: thread_(
{
InitializeCriticalSection( &cs_ );
thread_ = reinterpret_cast
/// Destructor
~SomeClass()
{
stop();
DeleteCriticalSection( &cs_ );
}
private:
/// Stops background task and wait until task is terminated
void stop()
{
CSGuard g( &cs_ );
exit_ = true;
WaitForSingleObject( thread_, INFINITE );
}
/// Background task
static void thread_func( void* args )
{
SomeClass* p_this = reinterpret_cast< SomeClass* >( args );
for( ;; ) // infinite loop
{
{
CSGuard g( &p_this->cs_ );
if( p_this->exit_ )
break;
}
Sleep( 100 ); // do some work
}
}
};
/// Test
int main()
{
SomeClass sc;
return 0;
}