blob: dd9eac36af3e68b978a627d69107f5ba67bf7bad [file] [log] [blame]
Jeff Thompsonfa306642013-06-17 15:06:57 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013, Regents of the University of California
4 * Alexander Afanasyev
5 * Zhenkai Zhu
6 *
7 * BSD license, See the LICENSE file for more information
8 *
9 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
10 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
11 */
12
13#ifndef EXECUTOR_H
14#define EXECUTOR_H
15
16#include <boost/function.hpp>
17#include <boost/shared_ptr.hpp>
18#include <boost/thread/condition_variable.hpp>
19#include <boost/thread/mutex.hpp>
20#include <boost/thread/locks.hpp>
21#include <boost/thread/thread.hpp>
22#include <deque>
23
24/* A very simple executor to execute submitted tasks immediately or
25 * in the future (depending on whether there is idle thread)
26 * A fixed number of threads are created for executing tasks;
27 * The policy is FIFO
28 * No cancellation of submitted tasks
29 */
30
31class Executor
32{
33public:
34 typedef boost::function<void ()> Job;
35
36 Executor(int poolSize);
37 ~Executor();
38
39 // execute the job immediately or sometime in the future
40 void
41 execute(const Job &job);
42
43 int
44 poolSize();
45
46// only for test
47 int
48 jobQueueSize();
49
50 void
51 start ();
52
53 void
54 shutdown ();
55
56private:
57 void
58 run();
59
60 Job
61 waitForJob();
62
63private:
64 typedef std::deque<Job> JobQueue;
65 typedef boost::mutex Mutex;
66 typedef boost::unique_lock<Mutex> Lock;
67 typedef boost::condition_variable Cond;
68 typedef boost::thread Thread;
69 typedef boost::thread_group ThreadGroup;
70 JobQueue m_queue;
71 Mutex m_mutex;
72 Cond m_cond;
73 ThreadGroup m_group;
74
75 volatile bool m_needStop;
76 int m_poolSize;
77};
78
79typedef boost::shared_ptr<Executor> ExecutorPtr;
80#endif // EXECUTOR_H