/*
	PIP - Platform Independent Primitives
	
	Stephan Fomenko

	This program 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 3 of the License, or
	(at your option) any later version.

	This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef PITHREADPOOLEXECUTOR_H
#define PITHREADPOOLEXECUTOR_H

#include "piblockingqueue.h"
#include <atomic>


class PIP_EXPORT PIThreadPoolExecutor {
public:
	explicit PIThreadPoolExecutor(int corePoolSize);

	virtual ~PIThreadPoolExecutor();

	/**
	 * \brief Executes the given task sometime in the future. The task execute in an existing pooled thread. If the task
	 * cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been
	 * reached.
	 *
	 * @param runnable not empty function for thread pool execution
	 */
	void execute(const std::function<void()> & runnable);

	void shutdownNow();

	/**
	 * \brief Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be
	 * accepted. Invocation has no additional effect if already shut down. This method does not wait for previously
	 * submitted tasks to complete execution. Use awaitTermination to do that.
	 */
	void shutdown();

	bool isShutdown() const;

	bool awaitTermination(int timeoutMs);

private:
	std::atomic_bool isShutdown_;
	PIBlockingQueue<std::function<void()> > taskQueue;
	PIVector<PIThread*> threadPool;
};

#endif // PITHREADPOOLEXECUTOR_H
