blob: 54a010864a456d1287865fc2b2567fbb9513464e [file] [log] [blame]
Zhenkai Zhuc8a54ca2013-01-18 20:25:41 -08001/* -*- 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 *
Alexander Afanasyev28ca3ed2013-01-24 23:17:15 -080018 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
19 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
Zhenkai Zhuc8a54ca2013-01-18 20:25:41 -080020 */
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
Alexander Afanasyevab5dff72013-01-24 10:25:28 -080032/* A very simple executor to execute submitted tasks immediately or
Zhenkai Zhuc8a54ca2013-01-18 20:25:41 -080033 * 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
39class Executor
40{
41public:
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
Alexander Afanasyevfc720362013-01-24 21:49:48 -080058 void
59 start ();
60
61 void
62 shutdown ();
63
Zhenkai Zhuc8a54ca2013-01-18 20:25:41 -080064private:
65 void
66 run();
67
68 Job
69 waitForJob();
70
71private:
72 typedef std::deque<Job> JobQueue;
73 typedef boost::mutex Mutex;
74 typedef boost::unique_lock<Mutex> Lock;
75 typedef boost::condition_variable Cond;
76 typedef boost::thread Thread;
77 typedef boost::thread_group ThreadGroup;
78 JobQueue m_queue;
79 Mutex m_mutex;
80 Cond m_cond;
81 ThreadGroup m_group;
Alexander Afanasyevab5dff72013-01-24 10:25:28 -080082
83 volatile bool m_needStop;
Alexander Afanasyevfc720362013-01-24 21:49:48 -080084 int m_poolSize;
Zhenkai Zhuc8a54ca2013-01-18 20:25:41 -080085};
86#endif // EXECUTOR_H