/*
 *  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 __ZTPOOLEXECUTOR_H__
#define __ZTPOOLEXECUTOR_H__

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

#include <assert.h>
#include <algorithm>

namespace ZThread {


/**
 * @class PoolExecutor
 *
 * @author Eric Crahen <crahen@cse.buffalo.edu>
 * @date <2002-03-04T20:28:39-0500>
 * @version 1.5.2
 *
 * A PoolExecutor is an abstraction for using a thread pool.
 * 
 * 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 the daemon threads, and 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 PoolExecutor
 * 
 * static Executor *executor = new PoolExecutor<true>(THREAD_COUNT); 
 * 
 * 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 PoolExecutor
 * 
 * int main() {
 * 
 *   Executor *executor = new PoolExecutor<false>(THREAD_COUNT);
 *
 *   // 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 PoolExecutor : public AbstractExecutor<L, Q> {
private:

  // Restricted constructors & operators
  PoolExecutor(PoolExecutor*);
  PoolExecutor(const PoolExecutor&);
  PoolExecutor& operator=(const PoolExecutor&);

protected:

  //! Typedef
  typedef std::deque<Thread*> WorkerList;

  //! Active worker threads
  WorkerList _activeWorkers;
  //! Idle worker threads
  WorkerList _unactiveWorkers;

  //! Minimum
  unsigned int _maxThreads;
  //! Maximum
  unsigned int _minThreads;

  virtual Thread* createWorker();


public:

  /**
   * Create a new Executor that uses a pool of 'n' threads
   * to execute submitted tasks.
   *
   * @param unsigned int - number of worker threads (n)
   */
  PoolExecutor(unsigned int min) throw() {

    _minThreads = min;
    _maxThreads = min;

  }


  /**
   * Create a new Executor that uses a pool of threads
   * to execute submitted tasks. 
   *
   * @param unsigned int - minimum number of worker threads
   * @param unsigned int - maximum number of worker threads
   * @param bool - daemon flag for static executors
   */ 
  PoolExecutor(unsigned int min, unsigned int max) throw() {

    _minThreads = min;
    _maxThreads = max;

  }


  /**
   * Destroy this Executor
   */
  virtual ~PoolExecutor() throw();

  /**
   * Change the maximum number of threads in the pool. As tasks are 
   * added to the Executor, more threads will be added as needed - 
   * up to the maximum number of worker threads set.
   *
   * @param unsigned int - new maximum number of worker threads.
   *
   * @exception Interrupted_Exception
   */
  void setMax(unsigned int max)
    throw(Synchronization_Exception) {

    Guard<LOCK> g(_lock);
    _maxThreads = max;
    
  }


  /**
   * Change the minimum number of threads in the pool. When currently
   * running tasks complete, and the Thread executing the task completes
   * it can be removed. A Thread will never be instantly killed because 
   * the minimum number of threads has changed. It is a gradual decline
   * in the number of worker threads.
   *
   * @param unsigned int - new minimum number of worker threads.
   *
   * @exception Interrupted_Exception
   */
  void setMin(unsigned int)
    throw(Synchronization_Exception) {

    Guard<LOCK> g(_lock);
    _minThreads = min;

  }

  /**
   * Get the current maximum number of threads
   *
   * @return unsigned int - current maximum
   *
   * @exception Interrupted_Exception
   */
  unsigned int getMax()
    throw(Synchronization_Exception) {

    Guard<LOCK> g(_lock);
    return _maxThreads;

  }

  /**
   * Get the current minimum number of threads
   *
   * @return unsigned int - current minimum
   *
   * @exception Interrupted_Exception
   */
  unsigned int getMin()
    throw(Synchronization_Exception) {

    Guard<LOCK> g(_lock);
    return _minThreads;

  }

  /**
   * Submit a new task
   *
   * @see Executor::execute(Runnable*)
   */
  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);
      
      if(_queue.isCanceled())
        throw Cancelation_Exception();
      
      // Increase threads working threads to minimum
      while(_activeWorkers.size() < _minThreads)
        addWorker();
    
      // Remove any threads over the maximum
      if(_activeWorkers.size() > _maxThreads)
        removeWorker();
    }
    
    _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);


  /**
   * Block until the executor becomes ready
   */
  virtual bool available() 
    throw(Synchronization_Exception) {

    if(_queue.isCanceled())
      return false;

    {

      Guard<LOCK> g(_lock);
      
      if(_minThreads < _maxThreads)
        return true;
    
    }

    return _queue.empty();

  }

  /**
   * 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 - current thread count of the internal worker pool
   *
   * @exception InterruptedException 
   */ 
  virtual unsigned int threadCount()
    throw(Synchronization_Exception) {

    Guard<LOCK> g(_lock);
    return _activeWorkers.size();

  }

 protected:

  /**
   * Internally used to manipulate the worker thread pool
   *
   * @exception InterruptedException 
   */
  void addWorker()
    throw(Synchronization_Exception) {
    
    // Create a new worker that will draw from this executor
    Thread* worker = createWorker();
    worker->start();
  
    _activeWorkers.push_back( worker );

  }

  /**
   * Internally used to manipulate the worker thread pool
   *
   * @exception InterruptedException 
   */
  void removeWorker()
    throw(Synchronization_Exception) {

    if( _activeWorkers.size() > 0 ) {

      // Remove from active list & cancel
      Thread* worker = _activeWorkers.front(); 
      _activeWorkers.pop_front();
      
      // Stop the worker, w/o interrupting any tasks
      worker->kill();
      
      // save in the unactive list
      _unactiveWorkers.push_back(worker);
      
    }
    
  }


};


template <bool DAEMON, class L, class Q>
Thread* PoolExecutor<DAEMON, L, Q>::createWorker() {

  if(!DAEMON)
    return new Worker<true>(&_queue);
  
  Thread* worker = new Worker<true>(&_queue);
  worker->setDaemon(true);

  return worker;

}


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

  if(DAEMON) {

    ZTDEBUG("Cleaning up daemon PoolWorkers\n");
  
    WorkerList::iterator i;
  
    for(i = _unactiveWorkers.begin(); i != _unactiveWorkers.end(); ++i) {
    
      try { 
        delete *i; 
      } catch(...) { ZTDEBUG("Error deleteing PoolWorker"); }
    
    }
  
  
    // Join an delete the active list
    for(i = _activeWorkers.begin(); i != _activeWorkers.end(); ++i) {
    
      try { 
        delete *i; 
      } catch(...) { ZTDEBUG("Error deleteing PoolWorker"); }
    
    }


  } else {

#ifndef NDEBUG
    
    if(_activeWorkers.size() > 0 || _unactiveWorkers.size() > 0) {
      
      ZTDEBUG("You are deleting a pool executor without having first \n");
      ZTDEBUG("join()'ed it. This will leave resources unclaimed and is not a good idea.\n");
      
    }
    
    assert(_activeWorkers.size() == 0 || _unactiveWorkers.size() == 0);
  
#endif

  }

}


template <bool DAEMON, class L, class Q>
void PoolExecutor<DAEMON, L, Q>::join() 
  throw(Synchronization_Exception) {

  if(DAEMON) {

    ZTDEBUG("This executor is using daemon threads and need not be joined\n");
    assert(0);

  } else {

    ZTDEBUG("Joining worker thread of PoolExecutor\n");
    bool success = true;

    WorkerList active, unactive;
    WorkerList::iterator i;


    { // guarded block

      Guard<Lockable> g(_lock);
    
      // local copies of the workers
      std::copy(_activeWorkers.begin(), _activeWorkers.end(), std::back_inserter(active));

      std::copy(_unactiveWorkers.begin(), _unactiveWorkers.end(), std::back_inserter(unactive));
    
      _unactiveWorkers.clear();
      _activeWorkers.clear();   

    }

    ZTDEBUG("Joining %d %d workers\n", active.size(), unactive.size() );

  // Join the unactive list
    for(i = unactive.begin();i != unactive.end(); ++i) {

      Thread* worker;

      try {

        worker = *i;
        worker->join();

      } catch(...) { success = false; }

    }
  

    // Join the active list
    for(i = active.begin();i != active.end(); ++i) {

      Thread* worker;

      try {

        worker = *i;
        worker->join();

      } catch(...) { success = false; }

    }

    // Once all the workers have stopped, reclaim thier resources
    for(i = unactive.begin();i != unactive.end(); ++i) {

      try { delete *i; } catch(...) {}

    }

    for(i = active.begin();i != active.end(); ++i) {

      try { delete *i; } catch(...) {}

    }

    if(!success)
      throw Interrupted_Exception();

  }

}


};

#endif


