Blame threadpool.h

d0530b
#ifndef THREADPOOL_H
d0530b
#define THREADPOOL_H
d0530b
d0530b
d0530b
#include <list></list>
d0530b
#include <deque></deque>
d0530b
#include <mutex></mutex>
d0530b
#include <thread></thread>
d0530b
#include <functional></functional>
d0530b
#include <condition_variable></condition_variable>
d0530b
d0530b
98bb38
#include "common.h"
541903
98bb38
98bb38
typedef Shared TaskOwner;
541903
541903
d0530b
class ThreadPool {
d0530b
public:
d0530b
	typedef unsigned long long TaskId;
d0530b
	typedef std::function<void()> Task;</void()>
d0530b
	
d0530b
	struct TaskDesc {
d0530b
		TaskId id;
98bb38
		TaskOwner::Handle::Weak owner;
d0530b
		Task task;
d0530b
		
d0530b
		inline TaskDesc():
d0530b
			id(), owner(), task(nullptr) { }
98bb38
		inline TaskDesc(TaskId id, const TaskOwner::Handle::Weak &owner, const Task &task):
d0530b
			id(id), owner(owner), task(task) { }
d0530b
	};
d0530b
d0530b
	struct Thread {
d0530b
		std::thread *thread;
d0530b
		std::condition_variable condition;
d0530b
		TaskId taskId;
98bb38
		TaskOwner::Handle taskOwner;
d0530b
		bool stopping;
d0530b
		
d0530b
		inline Thread():
d0530b
			thread(), taskId(), taskOwner(), stopping() { }
d0530b
	};
d0530b
	
d0530b
	typedef std::list<thread> ThreadList;</thread>
d0530b
	typedef std::deque<taskdesc> Queue;</taskdesc>
d0530b
	
d0530b
private:
d0530b
	std::mutex mutexStartStop;
d0530b
	std::mutex mutex;
d0530b
	std::condition_variable condition;
d0530b
	ThreadList threads;
d0530b
	Queue queue;
d0530b
	TaskId lastId;
d0530b
	
d0530b
	void threadRun(Thread &thread);
d0530b
	
d0530b
public:
d0530b
	ThreadPool();
d0530b
	~ThreadPool();
d0530b
	
98bb38
	TaskId enqueue(const Task &task, const TaskOwner::Handle &owner = nullptr);
541903
	int cancelById(TaskId id, bool wait = true);
98bb38
	int cancelByOwner(const TaskOwner::Handle &owner, bool wait = true);
541903
	int cancelAll(bool wait = true);
d0530b
	
d0530b
	void start(int count, bool cancelAllTasks = false);
d0530b
	inline void stop(bool cancelAllTasks = false)
d0530b
		{ start(0, cancelAllTasks); }
d0530b
};
d0530b
d0530b
d0530b
#endif