Boost logo

Boost Users :

From: Christian Henning (chhenning_at_[hidden])
Date: 2005-08-11 12:24:08


Thank you very much for the useful information. I think I have to
learn a lot more about the Posix threads.

This is now my Sequencer and I believe it is running correctly. But of
course, every feedback is welcome:

class Sequencer : private boost::noncopyable
{
public:

   Sequencer();

   ~Sequencer();

  void start();

  void stop();

private:

   enum teThreadState
   {
      _NOT_STARTED_ = 1,
      _RUNNING_ ,
      _STOPPED_
   };

private:

  void _run();

private:

   teThreadState volatile _eThreadState;

   bool volatile _bStarted;
   boost::mutex _oRunMutex;
   boost::condition _oRunCond;

   bool volatile _bStop;
   boost::mutex _oStopMutex;
   boost::condition _oStopCond;

   bool volatile _bTerminated;
   bool volatile _bTerminateSequencer;
   boost::mutex _oTerminateMutex;
   boost::condition _oTerminateCond;

   fActive<Sequencer> _oThread;
};

Sequencer::Sequencer()

   : _oThread()
   
   , _bStarted ( false )
   , _bStop ( false )

   , _bTerminateSequencer( false )
   , _bTerminated ( false )

   , _eThreadState( _NOT_STARTED_ )
{
   _oThread.create( this, _run );
}

Sequencer::~Sequencer()
{
   // signal the thread to terminate
   _bTerminateSequencer = true;

   // wake up the thread if it's sleeping
   _oRunCond.notify_one();

   // wait until the thread is terminated
   {
      boost::mutex::scoped_lock oLock( _oTerminateMutex );

      while( !_bTerminated )
         _oTerminateCond.wait( oLock );
   }
}

   void
Sequencer::start()
{
   _bStarted = true;
   _bStop = false;

   _oRunCond.notify_one();
}

   void
Sequencer::stop()
{
   boost::mutex::scoped_lock oLock ( _oStopMutex );

   _bStop = true;
   
   while( _eThreadState != _STOPPED_ )
      _oStopCond.wait( oLock );
}

   void
Sequencer::_run()
{
   boost::mutex::scoped_lock oLock( _oRunMutex );

   //wait until start() was called
   while( !_bStarted )
      _oRunCond.wait( oLock );

   _eThreadState = _RUNNING_;

   do
   {
      if( _bStop )
      {
         _eThreadState = _STOPPED_;

         _oStopCond.notify_one();
         
         while( _bStop )
            _oRunCond.wait( oLock );
      }

      _eThreadState = _RUNNING_;

   } while( !_bTerminateSequencer );

   _bTerminated = true;
   _oTerminateCond.notify_one();

   return;
}

If someone is interessted in the fActive template class, just let me
know. I think I should also put the thread inside the fActive class.

Thanks so much again, for the tips,
Christian


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net