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 | #include "executor.h" |
| 23 | |
| 24 | using namespace std; |
| 25 | using namespace boost; |
| 26 | |
| 27 | Executor::Executor(int poolSize) |
| 28 | { |
| 29 | for (int i = 0; i < poolSize; i++) |
| 30 | { |
| 31 | m_group.create_thread(bind(&Executor::run, this)); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | Executor::~Executor() |
| 36 | { |
| 37 | m_group.interrupt_all(); |
| 38 | } |
| 39 | |
| 40 | void |
| 41 | Executor::execute(const Job &job) |
| 42 | { |
| 43 | Lock lock(m_mutex); |
| 44 | bool queueWasEmpty = m_queue.empty(); |
| 45 | m_queue.push_back(job); |
| 46 | |
| 47 | // notify working threads if the queue was empty |
| 48 | if (queueWasEmpty) |
| 49 | { |
| 50 | m_cond.notify_one(); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | int |
| 55 | Executor::poolSize() |
| 56 | { |
| 57 | return m_group.size(); |
| 58 | } |
| 59 | |
| 60 | int |
| 61 | Executor::jobQueueSize() |
| 62 | { |
| 63 | Lock lock(m_mutex); |
| 64 | return m_queue.size(); |
| 65 | } |
| 66 | |
| 67 | void |
| 68 | Executor::run() |
| 69 | { |
| 70 | while(true) |
| 71 | { |
| 72 | Job job = waitForJob(); |
| 73 | |
| 74 | job(); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | Executor::Job |
| 79 | Executor::waitForJob() |
| 80 | { |
| 81 | Lock lock(m_mutex); |
| 82 | |
| 83 | // wait until job queue is not empty |
| 84 | while (m_queue.empty()) |
| 85 | { |
| 86 | m_cond.wait(lock); |
| 87 | } |
| 88 | |
| 89 | Job job = m_queue.front(); |
| 90 | m_queue.pop_front(); |
| 91 | return job; |
| 92 | } |