summaryrefslogtreecommitdiff
path: root/gi/pyp-topics/src/workers.hh
blob: 95b189477de3d75bfb2ac989ff625d1303b701e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/**
  Basic thread-pool tools using Boost.Thread.
  (Jan Botha, 7/2010)

  --Simple usage--
  Use SimpleWorker.
    Example, call a function that returns an int in a new thread:
    typedef boost::function<int()> JobType;
    JobType job = boost::bind(funcname);
      //or boost::bind(&class::funcname, this) for a member function
    SimpleWorker<JobType, int> worker(job);
    int result = worker.getResult(); //blocks until result is ready

  --Extended usage--
  Use WorkerPool, which uses Queuemt (a synchronized queue) and Worker.
  Example:
    (same context and typedef
    WorkerPool<JobType, int> pool(num_threads);
    JobType job = ...
    pool.addJob(job);
    ...
    pool.get_result(); //blocks until all workers are done, returns the some of their results.  
    
    Jobs added to a WorkerPool need to be the same type. A WorkerPool instance should not be reused (e.g. adding jobs) after calling get_result(). 
*/

#ifndef WORKERS_HH
#define WORKERS_HH

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <queue>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/future.hpp>
#include <boost/thread/condition.hpp>

#include <boost/date_time/posix_time/posix_time_types.hpp>
#include "timing.h"

/** Implements a synchronized queue*/
template<typename J>
class Queuemt
{

public:
    boost::condition_variable_any cond;
    const bool& running;

    Queuemt() { }
    Queuemt(const bool& running) : running(running), maxsize(0), qsize(0) 
    { 
    }

    ~Queuemt() { 
     }

    J pop()
    {
        J job;
        {
            boost::unique_lock<boost::shared_mutex> qlock(q_mutex);
            while (running && qsize == 0)
                cond.wait(qlock);

            if (qsize > 0)
            {
                job = q.front();
                q.pop();
                --qsize;      
            }
        }
        if (job)
            cond.notify_one();
        return job;

    }

    void push(J job)
    {
        {
            boost::unique_lock<boost::shared_mutex> lock(q_mutex);
            q.push(job);
            ++qsize;
        }
        if (qsize > maxsize)
            maxsize = qsize;
        
        cond.notify_one();
    }

    int getMaxsize()
    {
        return maxsize;
    }

    int size()
    {
        return qsize;
    }

private:
    boost::shared_mutex q_mutex;
    std::queue<J> q;
    int maxsize;
    volatile int qsize;
};


template<typename J, typename R>
class Worker
{
typedef boost::packaged_task<R> PackagedTask;
public:
    Worker(Queuemt<J>& queue, int id, int num_workers) :  
      q(queue), tasktime(0.0), id(id), num_workers(num_workers)
    {
        PackagedTask task(boost::bind(&Worker<J, R>::run, this));
        future = task.get_future();
        boost::thread t(boost::move(task));
    }

    R run() //this is called upon thread creation
    {
        R wresult = 0;
        while (isRunning())
        {
            J job = q.pop();

            if (job)
            {
                timer.Reset();
                wresult += job();
                tasktime += timer.Elapsed();
            }
        }
        return wresult;
    }

    R getResult()
    {
        if (!future.is_ready())
            future.wait();
        assert(future.is_ready());
        return future.get();
    }

    double getTaskTime()
    {
        return tasktime;
    }

private:

    Queuemt<J>& q;

    boost::unique_future<R> future;

    bool isRunning()
    {
        return q.running || q.size() > 0;
    }
    
    Timer timer;
    double tasktime;
    int id;
    int num_workers;
};

template<typename J, typename R>
class WorkerPool
{
typedef boost::packaged_task<R> PackagedTask;
typedef Worker<J,R> WJR;
typedef boost::ptr_vector<WJR> WorkerVector;
public:

    WorkerPool(int num_workers)
    {
        q.reset(new Queuemt<J>(running));
        running = true;
        for (int i = 0; i < num_workers; ++i)
            workers.push_back( new Worker<J, R>(*q, i, num_workers) );
    }

    ~WorkerPool()
    {
    }

    R get_result()
    {
        running = false;
        q->cond.notify_all();
        R tmp = 0;
        double tasktime = 0.0;
        for (typename WorkerVector::iterator it = workers.begin(); it != workers.end(); it++)
        {
            R res = it->getResult();
            tmp += res;
            //std::cerr << "tasktime: " << it->getTaskTime() << std::endl; 
            tasktime += it->getTaskTime();
        }
//        std::cerr << " maxQ = " << q->getMaxsize() << std::endl;
        return tmp;
    }

    void addJob(J job)
    {
        q->push(job);
    }

private:

    WorkerVector workers;

    boost::shared_ptr<Queuemt<J> > q;

    bool running;
};

///////////////////
template <typename J, typename R>
class SimpleWorker
{
typedef boost::packaged_task<R> PackagedTask;
public:
    SimpleWorker(J& job) : job(job), tasktime(0.0)
    {
        PackagedTask task(boost::bind(&SimpleWorker<J, R>::run, this));
        future = task.get_future();
        boost::thread t(boost::move(task));
    }

    R run() //this is called upon thread creation
    {
        R wresult = 0;

        assert(job);
        timer.Reset();
        wresult = job();
        tasktime = timer.Elapsed();
        std::cerr << tasktime << " s" << std::endl; 
        return wresult;
    }

    R getResult()
    {
        if (!future.is_ready())
            future.wait();
        assert(future.is_ready());
        return future.get();
    }

    double getTaskTime()
    {
        return tasktime;
    }

private:

    J job;

    boost::unique_future<R> future;

    Timer timer;
    double tasktime;

};



#endif