erebus

diff liberebus/src/threadpool.h @ 26:c8a6fb04fefa

multithreadededit
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 01 Jun 2014 19:19:40 +0300
parents 4336acf8389d
children d15ee526daa6
line diff
     1.1 --- a/liberebus/src/threadpool.h	Sat May 31 06:21:09 2014 +0300
     1.2 +++ b/liberebus/src/threadpool.h	Sun Jun 01 19:19:40 2014 +0300
     1.3 @@ -1,30 +1,53 @@
     1.4 -#ifndef THREAD_POOL_H_
     1.5 -#define THREAD_POOL_H_
     1.6 -
     1.7 -#include <list>
     1.8 -#include <functional>
     1.9 -#include <thread>
    1.10 -#include <mutex>
    1.11 -#include <condition_variable>
    1.12 -
    1.13 -class ThreadPool {
    1.14 -private:
    1.15 -	int num_threads;
    1.16 -	std::thread *thread;	// array of threads
    1.17 -
    1.18 -	std::list<std::function<void ()>> workq;
    1.19 -	std::mutex workq_mutex;
    1.20 -	std::condition_variable condvar;
    1.21 -
    1.22 -	bool quit;
    1.23 -
    1.24 -	void thread_func();
    1.25 -
    1.26 -public:
    1.27 -	ThreadPool(int num_threads = -1);
    1.28 -	~ThreadPool();
    1.29 -
    1.30 -	void add_work(std::function<void ()> func);
    1.31 -};
    1.32 -
    1.33 -#endif	// THREAD_POOL_H_
    1.34 \ No newline at end of file
    1.35 +#ifndef THREAD_POOL_H_
    1.36 +#define THREAD_POOL_H_
    1.37 +
    1.38 +#include <list>
    1.39 +#include <functional>
    1.40 +#include <thread>
    1.41 +#include <mutex>
    1.42 +#include <condition_variable>
    1.43 +
    1.44 +class ThreadPool {
    1.45 +private:
    1.46 +	int num_threads;
    1.47 +	std::thread *thread;	// array of threads
    1.48 +
    1.49 +	struct WorkItem {
    1.50 +		std::function<void ()> work;
    1.51 +		std::function<void ()> done;
    1.52 +	};
    1.53 +
    1.54 +	int qsize;
    1.55 +	std::list<WorkItem> workq;
    1.56 +	mutable std::mutex workq_mutex;
    1.57 +	std::condition_variable workq_condvar;
    1.58 +
    1.59 +	int nactive;	// number of active workers (not sleeping)
    1.60 +
    1.61 +	// condvar used by wait
    1.62 +	std::condition_variable done_condvar;
    1.63 +
    1.64 +	bool quit;
    1.65 +
    1.66 +	void thread_func();
    1.67 +
    1.68 +public:
    1.69 +	ThreadPool(int num_threads = -1);
    1.70 +	~ThreadPool();
    1.71 +
    1.72 +	void add_work(std::function<void ()> func);
    1.73 +	void add_work(std::function<void ()> work_func, std::function<void ()> done_func);
    1.74 +
    1.75 +	// returns the number of queued work items
    1.76 +	int queued() const;
    1.77 +	// returns the number of active threads
    1.78 +	int active() const;
    1.79 +	// returns number of pending work items (both in the queue and active)
    1.80 +	int pending() const;
    1.81 +
    1.82 +	// waits for all work to be completed
    1.83 +	long wait();
    1.84 +	long wait(long timeout);
    1.85 +};
    1.86 +
    1.87 +#endif	// THREAD_POOL_H_