/* Network-Integrated Multimedia Middleware (NMM)
 * http://www.motama.com/nmm.html
 *  
 * Copyright (C) 2006-2007
 * Motama GmbH, Saarbruecken, Germany
 * http://www.motama.com
 *  
 * This file is part of NMM. 
 * 
 * NMM is free software; you can redistribute it and/or modify it    
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; only version 2 of the License.      
 * 
 * NMM is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 
 * License for more details.  
 * 
 * You should have received a copy of the GNU General Public License 
 * along with NMM; if not, write to the Free Software Foundation,    
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
#ifndef NMM_THREADEDOBJECT_HPP
#define NMM_THREADEDOBJECT_HPP

#include "nmm/nmm_prefix.hpp"

#include "Thread.hpp"

namespace NMM {
 /** Base class for all classes that need their own. The method run is executed in a separate thread and must be 
  * implemented by all sub-classes.
  */
  class ThreadedObject {
  public:
    /** Constructor
     */
    ThreadedObject() : running(false) {}
    
    /** Destructor
     */
    virtual ~ThreadedObject() { deactivateThread();}
    
    /** Returns a refernce to the thread.
     *  \return a refernce to the thread
     */
    inline const Thread& getThread() {return thread;}
    
  protected:
    /** Abstract run-method which is started in the thread. This method must be implemented by all sub-classes.
     */
    virtual void run() = 0;


    /** Activates the thread and starts the run method.
     */
    inline void activateThread()   { if (isRunning()) return; running = true; thread.start(static_run, static_cast<void *>(this)); }

    /** Deactivates the thread and waits until method run returns.
     */
    inline void deactivateThread() { if (isRunning()) {running = false; thread.join();}}

    /** Returns true if the thread has been activated, otherwise false.
     *
     * @return true if the thread has been activated, otherwise false
     */
    inline bool isRunning() const  { return running; }
  private:

    /** Internal helper method that starts the run method in its own thread  
     */  
    static void* static_run(void* obj) { static_cast<ThreadedObject*>(obj)->run();  return 0;}
    
    Thread thread;
    bool running;
  };
}

#include "nmm/nmm_suffix.hpp"

#endif // NMM_THREADEDOBJECT_HPP
