/*
 *  ZThreads, a platform-independant, multithreading and 
 *  synchroniation library
 *
 *  Copyright (C) 2000-2002, Eric Crahen, See LGPL.TXT for details
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 *  SUNY @ Buffalo, hereby disclaims all copyright interest in the
 *  ZThreads library written by Eric Crahen
 */

#ifndef __ZTASYNCEXECUTOR_H__
#define __ZTASYNCEXECUTOR_H__

#include "zthread/ZThread.h"
#include "zthread/AbstractExecutor.h"
#include "zthread/Worker.h"

#include <assert.h>

namespace ZThread {

/**
 * @class AsyncExecutor
 *
 * @author Eric Crahen <crahen@cse.buffalo.edu>
 * @date <2002-03-04T20:28:29-0500>
 * @version 1.5.2
 *
 * An AsyncExecutor executes submitted tasks in another thread. All 
 * tasks enqueued are executed by a single Worker thread. 
 * 
 * STATIC/NON-STATIC EXECUTORS:
 * 
 * All static executors should be marked as Daemon's using the template
 * parameter. If the executor is non-static then it should not be marked 
 * as a daemon.
 *
 * Static executors will use daemon threads, so static executors do not need 
 * to be join()ed - however, they still need to be cancel()ed. 
 * This allows static executors to complete thier tasks after
 * main exits, and solves static deadlock & deconstruction problems.
 *
 * @code
 *
 * // Proper use of a static AsyncExecutor
 * 
 * static Executor *executor = new AsyncExecutor<true>; 
 * 
 * int main() {
 *
 *   // Add tasks
 *
 *   executor->cancel();
 *
 * }
 *
 * @endcode
 *
 * Static executors can not be cancled from within thier destructors. The
 * system will not execute the destructors for static objects until the 
 * threads have all been joined. Worker threads will not exit until the 
 * executor has been cancled. This will lead to a deadlock situation.
 * 
 * @code
 *
 * // Proper use of a non-static AsyncExecutor
 * 
 * int main() {
 * 
 *   Executor *executor = new AsyncExecutor<false>;
 *
 *   // Add tasks
 *
 *   executor->cancel();
 *   executor->join();
 * }
 *
 * @endcode
 *
 * A template parameter was chosen because it allows only the
 * code needed to implement that type of executor to be used, and eliminates
 * the need for a daemon flag within the executor and a series of constant
 * checks to take the approriate action. 
 * 
 * The template also better reflects the nature of the choice of executor type.
 * A static executor will not change and suddenly not act static, and vice-versa.
 *
 */

template <bool DAEMON, class L = Mutex, class Q = MonitoredQueue<Runnable*> >
class ZTHREAD_API AsyncExecutor : public AbstractExecutor<L, Q> {
private:

  AsyncExecutor(AsyncExecutor*);
  AsyncExecutor(const AsyncExecutor&);
  AsyncExecutor& operator=(const AsyncExecutor&);

protected:
  
  //! Worker thread
  Thread* _worker;                    

  /**
   * Default worker implementation will consume tasks
   */
  virtual Thread* createWorker() {
    return new Worker<true>(&_queue);
  }


public:

  /**
   * Create a new AsyncExecutor, the actual initialization of any
   * underlying resources used in constructing this Executor is 
   * deferred until the first task is executed.
   *
   * @param bool - optionally daemon flag the thread, for static 
   * executors
   */
  AsyncExecutor()
    throw(Synchronization_Exception);

  /**
   * Destroy the AsyncExecutor. 
   *
   * @pre The Executor should be joined prior to its destruction.
   */
  virtual ~AsyncExecutor() throw();

  /**
   * Enqueue another task for execution. This does not block the caller
   * very long. As soon as the task is enqueued the function will return;
   * the task will eventually be executed by this Executor.
   *
   * @param Runnable task - task to execute
   * @exception InterruptedException 
   *
   * @pre The executor must not be canceled. A canceled
   * executor will ignore execute() requests.
   *
   * @post The given task will be executed as soon as 
   * possible by the executor
   */
  virtual void execute(Runnable* task)
    throw(Synchronization_Exception) {

    if(_queue.isCanceled()) // Avoid excess locking in the canceled state
      throw Cancelation_Exception();

    Guard<LOCK> g(_lock);

    // Enqueue the task
    _queue.add(task); 

  }

  /**
   * Wait for this Executor to complete. The calling thread is
   * blocked until the last task has been completed by this executor
   * or until the calling thread has been interrupted.
   *
   * @exception InterruptedException 
   */
  virtual void join() 
    throw(Synchronization_Exception);


  /**
   * Count of active threads operation on behalf of this executor
   *
   * This does not guarantee that another thread won't have submitted a
   * task that changes the number of executing threads before some action 
   * is taken in response to this. However, it is useful as a general 
   * heuristic
   * 
   * @return unsigned int
   * @exception InterruptedException 
   */ 
  inline virtual unsigned int threadCount()
    throw(Synchronization_Exception) {
    
    return (_queue.isCanceled()) ? 1 : 0;

  }


};

/**
 * Default template will create  non-daemon executors
 */
template <bool DAEMON, class L, class Q>
AsyncExecutor<DAEMON, L, Q>::AsyncExecutor()
  throw(Synchronization_Exception) {

  _worker = createWorker();

  try {

    if(DAEMON) {

      _worker->setDaemon(true);
      _worker->start();

    } else
      _worker->start();

  } catch(...) {

    delete _worker;
    throw;

  }

}


/**
 * Default template will create non-daemon executors
 */
template <bool DAEMON, class L, class Q>
void AsyncExecutor<DAEMON, L, Q>::join() 
  throw(Synchronization_Exception) {

  if(DAEMON) {

    assert(0); //This worker is a daemon thread & needs not be joined

  } else {

    // Reduce contention in the joined state
    if(_worker == 0)
      return;
    
    Guard<LOCK> g(_lock);
    
    if(_worker == 0)
      return;
    
    // Release these resources when joined.
    _worker->join();
    
    delete _worker;
    _worker = 0;

  }

}


template<bool DAEMON, class L, class Q>
AsyncExecutor<DAEMON, L, Q>::~AsyncExecutor() throw() {
   
  
  if(DAEMON) {

    if(_worker != 0) 
      delete _worker;
    
  } else {

    if(_worker != 0) 
      assert(0); // Non-daemon executors should be join()ed first

  }

}


};

#endif




