00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #ifndef moses_ThreadPool_h
00023 #define moses_ThreadPool_h
00024
00025 #include <iostream>
00026 #include <queue>
00027 #include <vector>
00028
00029 #ifdef WITH_THREADS
00030 #include <boost/bind.hpp>
00031 #include <boost/thread.hpp>
00032 #endif
00033
00034 #ifdef BOOST_HAS_PTHREADS
00035 #include <pthread.h>
00036 #endif
00037
00038
00039
00040
00041
00046 namespace Moses {
00047
00051 class Task
00052 {
00053 public:
00054 virtual void Run() = 0;
00055 virtual bool DeleteAfterExecution() { return true; }
00056 virtual ~Task() {}
00057 };
00058
00059 #ifdef WITH_THREADS
00060
00061 class ThreadPool
00062 {
00063 public:
00067 explicit ThreadPool(size_t numThreads);
00068
00069 ~ThreadPool() {
00070 Stop();
00071 }
00072
00076 void Submit(Task* task);
00077
00082 void Stop(bool processRemainingJobs = false);
00083
00084 private:
00088 void Execute();
00089
00090 std::queue<Task*> m_tasks;
00091 boost::thread_group m_threads;
00092 boost::mutex m_mutex;
00093 boost::condition_variable m_threadNeeded;
00094 boost::condition_variable m_threadAvailable;
00095 bool m_stopped;
00096 bool m_stopping;
00097 };
00098
00099 class TestTask : public Task
00100 {
00101 public:
00102 TestTask(int id) : m_id(id) {}
00103
00104 virtual void Run() {
00105 #ifdef BOOST_HAS_PTHREADS
00106 pthread_t tid = pthread_self();
00107 #else
00108 pthread_t tid = 0;
00109 #endif
00110 std::cerr << "Executing " << m_id << " in thread id " << tid << std::endl;
00111 }
00112
00113 virtual ~TestTask() {}
00114
00115 private:
00116 int m_id;
00117 };
00118
00119 #endif //WITH_THREADS
00120
00121 }
00122 #endif // moses_ThreadPool_h