00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #ifndef GRIDTHREADPOOL_HPP_
00011 #define GRIDTHREADPOOL_HPP_
00012
00013 #include <vector>
00014 #include <queue>
00015 #include <memory>
00016 #include <stdexcept>
00017
00018 #include <boost/thread/thread.hpp>
00019 #include <boost/thread/condition_variable.hpp>
00020 #include <boost/function.hpp>
00021
00022 #include "gridgain/gridclienttypedef.hpp"
00023
00028 class GridThreadPoolIsShutdownException: public std::logic_error {
00029 public:
00030 GridThreadPoolIsShutdownException();
00031 };
00032
00039 class GridThreadPoolTask {
00040 public:
00041 virtual ~GridThreadPoolTask() {}
00042
00046 virtual void run() = 0;
00047
00052 virtual void cancel() = 0;
00053 };
00054
00056 typedef std::shared_ptr<GridThreadPoolTask> TGridThreadPoolTaskPtr;
00057
00062 class GridSimpleThreadPoolTask: public GridThreadPoolTask {
00066 virtual void cancel() {}
00067 };
00068
00079 class GridThreadPool: private boost::noncopyable {
00080 public:
00086 GridThreadPool(unsigned int nthreads);
00087
00093 virtual ~GridThreadPool();
00094
00102 void execute(TGridThreadPoolTaskPtr& task);
00103
00107 size_t queueSize() const;
00108
00117 void waitForEmptyQueue();
00118
00130 void shutdown();
00131
00132 private:
00141 template<class T, class ImplT = std::list<T> >
00142 class SynchronizedBlockingQueue {
00144 typedef typename ImplT::iterator Iterator;
00145
00146 public:
00156 void offer(const T& elem) {
00157 {
00158 boost::lock_guard<boost::mutex> guard(mux);
00159
00160 impl.push_back(elem);
00161 }
00162
00163
00164 emptyCond.notify_one();
00165 }
00166
00174 T poll() {
00175 boost::unique_lock<boost::mutex> lock(mux);
00176
00177
00178 while (impl.empty())
00179 emptyCond.wait(lock);
00180
00181 T ret = impl.front();
00182 impl.pop_front();
00183
00184 if (impl.empty())
00185
00186 nonEmptyCond.notify_one();
00187
00188 return ret;
00189 }
00190
00194 size_t size() const {
00195 boost::lock_guard<boost::mutex> guard(mux);
00196
00197 return impl.size();
00198 }
00199
00204 void waitUntilEmpty() {
00205 boost::unique_lock<boost::mutex> lock(mux);
00206
00207
00208 while (!impl.empty())
00209 nonEmptyCond.wait(lock);
00210
00211
00212 }
00213
00219 void forEach(std::function<void (T)> f) {
00220 boost::lock_guard<boost::mutex> guard(mux);
00221
00222 for (typename ImplT::iterator i = impl.begin(); i != impl.end(); i++)
00223 f(*i);
00224 }
00225
00226 private:
00228 ImplT impl;
00229
00231 mutable boost::mutex mux;
00232
00234 boost::condition_variable emptyCond;
00235
00237 boost::condition_variable nonEmptyCond;
00238 };
00239
00243 void worker();
00244
00246 typedef std::vector<boost::thread> TThreadList;
00247 TThreadList threads;
00248
00250 SynchronizedBlockingQueue<TGridThreadPoolTaskPtr> tasks;
00251
00253 TGridAtomicBool isShutdown;
00254 };
00255
00256 typedef std::shared_ptr<GridThreadPool> TGridThreadPoolPtr;
00257
00258 #endif