Zhenkai Zhu | c8a54ca | 2013-01-18 20:25:41 -0800 | [diff] [blame] | 1 | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */ |
| 2 | /* |
| 3 | * Copyright (c) 2013 University of California, Los Angeles |
| 4 | * |
| 5 | * This program is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License version 2 as |
| 7 | * published by the Free Software Foundation; |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 17 | * |
| 18 | * Zhenkai Zhu <zhenkai@cs.ucla.edu> |
| 19 | * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> |
| 20 | */ |
| 21 | |
| 22 | #ifndef EXECUTOR_H |
| 23 | #define EXECUTOR_H |
| 24 | |
| 25 | #include <boost/function.hpp> |
| 26 | #include <boost/thread/condition_variable.hpp> |
| 27 | #include <boost/thread/mutex.hpp> |
| 28 | #include <boost/thread/locks.hpp> |
| 29 | #include <boost/thread/thread.hpp> |
| 30 | #include <deque> |
| 31 | |
| 32 | /* A very simple executor to execute submitted tasks immediately or |
| 33 | * in the future (depending on whether there is idle thread) |
| 34 | * A fixed number of threads are created for executing tasks; |
| 35 | * The policy is FIFO |
| 36 | * No cancellation of submitted tasks |
| 37 | */ |
| 38 | |
| 39 | class Executor |
| 40 | { |
| 41 | public: |
| 42 | typedef boost::function<void ()> Job; |
| 43 | |
| 44 | Executor(int poolSize); |
| 45 | ~Executor(); |
| 46 | |
| 47 | // execute the job immediately or sometime in the future |
| 48 | void |
| 49 | execute(const Job &job); |
| 50 | |
| 51 | int |
| 52 | poolSize(); |
| 53 | |
| 54 | // only for test |
| 55 | int |
| 56 | jobQueueSize(); |
| 57 | |
| 58 | private: |
| 59 | void |
| 60 | run(); |
| 61 | |
| 62 | Job |
| 63 | waitForJob(); |
| 64 | |
| 65 | private: |
| 66 | typedef std::deque<Job> JobQueue; |
| 67 | typedef boost::mutex Mutex; |
| 68 | typedef boost::unique_lock<Mutex> Lock; |
| 69 | typedef boost::condition_variable Cond; |
| 70 | typedef boost::thread Thread; |
| 71 | typedef boost::thread_group ThreadGroup; |
| 72 | JobQueue m_queue; |
| 73 | Mutex m_mutex; |
| 74 | Cond m_cond; |
| 75 | ThreadGroup m_group; |
| 76 | }; |
| 77 | #endif // EXECUTOR_H |