threading.h 9.87 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 *  This file is part of the MR utility library.
 *
 *  This code is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This code is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this code; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/* Copyright (C) 2019 Peter Bell, Max-Planck-Society
Martin Reinecke's avatar
Martin Reinecke committed
20
   Authors: Peter Bell, Martin Reinecke */
Martin Reinecke's avatar
Martin Reinecke committed
21

Martin Reinecke's avatar
Martin Reinecke committed
22
23
24
#ifndef MRUTIL_THREADING_H
#define MRUTIL_THREADING_H

Martin Reinecke's avatar
Martin Reinecke committed
25
#ifndef MRUTIL_NO_THREADING
Martin Reinecke's avatar
Martin Reinecke committed
26
27
28
29
30
31
32
33
#include <cstdlib>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <queue>
#include <atomic>
#include <functional>
#include <vector>
Martin Reinecke's avatar
Martin Reinecke committed
34
35
#if __has_include(<pthread.h>)
#include <pthread.h>
Martin Reinecke's avatar
Martin Reinecke committed
36
#endif
Martin Reinecke's avatar
Martin Reinecke committed
37
#endif
Martin Reinecke's avatar
Martin Reinecke committed
38

Martin Reinecke's avatar
Martin Reinecke committed
39
40
namespace mr {

Martin Reinecke's avatar
Martin Reinecke committed
41
namespace detail_threading {
Martin Reinecke's avatar
Martin Reinecke committed
42
43
44

using namespace std;

Martin Reinecke's avatar
Martin Reinecke committed
45
46
#ifndef MRUTIL_NO_THREADING
static const size_t max_threads_ = max(1u, thread::hardware_concurrency());
Martin Reinecke's avatar
Martin Reinecke committed
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

class latch
  {
    atomic<size_t> num_left_;
    mutex mut_;
    condition_variable completed_;
    using lock_t = unique_lock<mutex>;

  public:
    latch(size_t n): num_left_(n) {}

    void count_down()
      {
      lock_t lock(mut_);
      if (--num_left_)
        return;
      completed_.notify_all();
      }

    void wait()
      {
      lock_t lock(mut_);
      completed_.wait(lock, [this]{ return is_ready(); });
      }
    bool is_ready() { return num_left_ == 0; }
  };

template <typename T> class concurrent_queue
  {
    queue<T> q_;
    mutex mut_;
    condition_variable item_added_;
    bool shutdown_;
    using lock_t = unique_lock<mutex>;

  public:
    concurrent_queue(): shutdown_(false) {}

    void push(T val)
      {
      {
      lock_t lock(mut_);
      if (shutdown_)
        throw runtime_error("Item added to queue after shutdown");
      q_.push(move(val));
      }
      item_added_.notify_one();
      }

    bool pop(T & val)
      {
      lock_t lock(mut_);
      item_added_.wait(lock, [this] { return (!q_.empty() || shutdown_); });
      if (q_.empty())
        return false;  // We are shutting down

      val = std::move(q_.front());
      q_.pop();
      return true;
      }

    void shutdown()
      {
      {
      lock_t lock(mut_);
      shutdown_ = true;
      }
      item_added_.notify_all();
      }

    void restart() { shutdown_ = false; }
  };

class thread_pool
  {
    concurrent_queue<function<void()>> work_queue_;
    vector<thread> threads_;

    void worker_main()
      {
      function<void()> work;
      while (work_queue_.pop(work))
        work();
      }

    void create_threads()
      {
      size_t nthreads = threads_.size();
      for (size_t i=0; i<nthreads; ++i)
        {
        try { threads_[i] = thread([this]{ worker_main(); }); }
        catch (...)
          {
          shutdown();
          throw;
          }
        }
      }

  public:
    explicit thread_pool(size_t nthreads):
      threads_(nthreads)
      { create_threads(); }

Martin Reinecke's avatar
Martin Reinecke committed
151
    thread_pool(): thread_pool(max_threads_) {}
Martin Reinecke's avatar
Martin Reinecke committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

    ~thread_pool() { shutdown(); }

    void submit(function<void()> work)
      {
      work_queue_.push(move(work));
      }

    void shutdown()
      {
      work_queue_.shutdown();
      for (auto &thread : threads_)
        if (thread.joinable())
          thread.join();
      }

    void restart()
      {
      work_queue_.restart();
      create_threads();
      }
  };

Martin Reinecke's avatar
rework    
Martin Reinecke committed
175
inline thread_pool &get_pool()
Martin Reinecke's avatar
Martin Reinecke committed
176
177
  {
  static thread_pool pool;
Martin Reinecke's avatar
Martin Reinecke committed
178
#if __has_include(<pthread.h>)
Martin Reinecke's avatar
Martin Reinecke committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
  static once_flag f;
  call_once(f,
    []{
    pthread_atfork(
      +[]{ get_pool().shutdown(); },  // prepare
      +[]{ get_pool().restart(); },   // parent
      +[]{ get_pool().restart(); }    // child
      );
    });
#endif

  return pool;
  }

Martin Reinecke's avatar
rework    
Martin Reinecke committed
193
struct Range
Martin Reinecke's avatar
Martin Reinecke committed
194
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
195
196
197
198
199
  size_t lo, hi;
  Range() : lo(0), hi(0) {}
  Range(size_t lo_, size_t hi_) : lo(lo_), hi(hi_) {}
  operator bool() const { return hi>lo; }
  };
Martin Reinecke's avatar
Martin Reinecke committed
200

Martin Reinecke's avatar
rework    
Martin Reinecke committed
201
class Distribution
Martin Reinecke's avatar
Martin Reinecke committed
202
203
204
205
206
207
208
209
210
  {
  private:
    size_t nthreads_;
    mutex mut_;
    size_t nwork_;
    size_t cur_;
    size_t chunksize_;
    double fact_max_;
    vector<size_t> nextstart;
Martin Reinecke's avatar
Martin Reinecke committed
211
    enum SchedMode { SINGLE, STATIC, DYNAMIC };
Martin Reinecke's avatar
Martin Reinecke committed
212
213
    SchedMode mode;
    bool single_done;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
214
215

    template <typename Func> void thread_map(Func f);
Martin Reinecke's avatar
Martin Reinecke committed
216
217
218
219
220
221
222
223
224

  public:
    size_t nthreads() const { return nthreads_; }

    template<typename Func> void execSingle(size_t nwork, Func f)
      {
      mode = SINGLE;
      single_done = false;
      nwork_ = nwork;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
225
226
      nthreads_ = 1;
      thread_map(move(f));
Martin Reinecke's avatar
Martin Reinecke committed
227
228
229
230
231
      }
    template<typename Func> void execStatic(size_t nwork,
      size_t nthreads, size_t chunksize, Func f)
      {
      mode = STATIC;
Martin Reinecke's avatar
Martin Reinecke committed
232
      nthreads_ = (nthreads==0) ? max_threads_ : nthreads;
Martin Reinecke's avatar
Martin Reinecke committed
233
234
235
236
237
238
239
      nwork_ = nwork;
      chunksize_ = (chunksize<1) ? (nwork_+nthreads_-1)/nthreads_
                                 : chunksize;
      if (chunksize_>=nwork_) return execSingle(nwork_, move(f));
      nextstart.resize(nthreads_);
      for (size_t i=0; i<nextstart.size(); ++i)
        nextstart[i] = i*chunksize_;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
240
      thread_map(move(f));
Martin Reinecke's avatar
Martin Reinecke committed
241
242
243
244
245
      }
    template<typename Func> void execDynamic(size_t nwork,
      size_t nthreads, size_t chunksize_min, double fact_max, Func f)
      {
      mode = DYNAMIC;
Martin Reinecke's avatar
Martin Reinecke committed
246
      nthreads_ = (nthreads==0) ? max_threads_ : nthreads;
Martin Reinecke's avatar
Martin Reinecke committed
247
248
249
250
251
252
      nwork_ = nwork;
      chunksize_ = (chunksize_min<1) ? 1 : chunksize_min;
      if (chunksize_*nthreads_>=nwork_)
        return execStatic(nwork, nthreads, 0, move(f));
      fact_max_ = fact_max;
      cur_ = 0;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
253
      thread_map(move(f));
Martin Reinecke's avatar
Martin Reinecke committed
254
      }
Martin Reinecke's avatar
rework    
Martin Reinecke committed
255
256
257
258
259
260
261
262
263
    template<typename Func> void execParallel(size_t nthreads, Func f)
      {
      mode = STATIC;
      nthreads_ = (nthreads==0) ? max_threads_ : nthreads;
      nwork_ = nthreads_;
      chunksize_ = 1;
      thread_map(move(f));
      }
    Range getNext(size_t thread_id)
Martin Reinecke's avatar
Martin Reinecke committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
      {
      switch (mode)
        {
        case SINGLE:
          {
          if (single_done) return Range();
          single_done=true;
          return Range(0, nwork_);
          }
        case STATIC:
          {
          if (nextstart[thread_id]>=nwork_) return Range();
          size_t lo=nextstart[thread_id];
          size_t hi=min(lo+chunksize_,nwork_);
          nextstart[thread_id] += nthreads_*chunksize_;
          return Range(lo, hi);
          }
        case DYNAMIC:
          {
          unique_lock<mutex> lck(mut_);
          if (cur_>=nwork_) return Range();
          auto rem = nwork_-cur_;
          size_t tmp = size_t((fact_max_*rem)/nthreads_);
          auto sz = min(rem, max(chunksize_, tmp));
          size_t lo=cur_;
          cur_+=sz;
          size_t hi=cur_;
          return Range(lo, hi);
          }
        }
      return Range();
      }
  };

Martin Reinecke's avatar
rework    
Martin Reinecke committed
298
class Scheduler
Martin Reinecke's avatar
Martin Reinecke committed
299
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
  private:
    Distribution &dist_;
    size_t ithread_;

  public:
    Scheduler(Distribution &dist, size_t ithread)
      : dist_(dist), ithread_(ithread) {}
    size_t num_threads() const { return dist_.nthreads(); }
    size_t thread_num() const { return ithread_; }
    Range getNext() { return dist_.getNext(ithread_); }
  };

template <typename Func> void Distribution::thread_map(Func f)
  {
  auto & pool = get_pool();
  latch counter(nthreads_);
  exception_ptr ex;
  mutex ex_mut;
  for (size_t i=0; i<nthreads_; ++i)
    {
    pool.submit(
      [this, &f, i, &counter, &ex, &ex_mut] {
      try
        {
        Scheduler sched(*this, i);
        f(sched);
        }
      catch (...)
        {
        lock_guard<mutex> lock(ex_mut);
        ex = current_exception();
        }
      counter.count_down();
      });
    }
  counter.wait();
  if (ex)
    rethrow_exception(ex);
Martin Reinecke's avatar
Martin Reinecke committed
338
339
340
341
342
343
  }

#else

constexpr size_t max_threads_ = 1;

Martin Reinecke's avatar
rework    
Martin Reinecke committed
344
class Sched0
Martin Reinecke's avatar
Martin Reinecke committed
345
346
347
348
349
350
351
352
353
354
  {
  private:
    size_t nwork_;

  public:
    size_t nthreads() const { return 1; }

    template<typename Func> void execSingle(size_t nwork, Func f)
      {
      nwork_ = nwork;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
355
      f(Scheduler(*this,0));
Martin Reinecke's avatar
Martin Reinecke committed
356
357
358
359
360
361
362
363
364
365
      }
    template<typename Func> void execStatic(size_t nwork,
      size_t /*nthreads*/, size_t /*chunksize*/, Func f)
      {  execSingle(nwork, move(f)); }
    template<typename Func> void execDynamic(size_t nwork,
      size_t /*nthreads*/, size_t /*chunksize_min*/, double /*fact_max*/,
      Func f)
      {  execSingle(nwork, move(f)); }
    Range getNext()
      {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
366
      Range res(0, nwork_);
Martin Reinecke's avatar
Martin Reinecke committed
367
      nwork_=0;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
368
      return res;
Martin Reinecke's avatar
Martin Reinecke committed
369
370
371
372
373
374
375
376
      }
  };

template<typename Func> void execParallel(size_t /*nthreads*/, Func f)
  { f(); }

#endif

Martin Reinecke's avatar
rework    
Martin Reinecke committed
377
378
namespace {

Martin Reinecke's avatar
Martin Reinecke committed
379
380
template<typename Func> void execSingle(size_t nwork, Func f)
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
381
382
  Distribution dist;
  dist.execSingle(nwork, move(f));
Martin Reinecke's avatar
Martin Reinecke committed
383
384
385
386
  }
template<typename Func> void execStatic(size_t nwork,
  size_t nthreads, size_t chunksize, Func f)
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
387
388
  Distribution dist;
  dist.execStatic(nwork, nthreads, chunksize, move(f));
Martin Reinecke's avatar
Martin Reinecke committed
389
390
391
392
  }
template<typename Func> void execDynamic(size_t nwork,
  size_t nthreads, size_t chunksize_min, Func f)
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
393
394
  Distribution dist;
  dist.execDynamic(nwork, nthreads, chunksize_min, 0., move(f));
Martin Reinecke's avatar
Martin Reinecke committed
395
396
397
398
  }
template<typename Func> void execGuided(size_t nwork,
  size_t nthreads, size_t chunksize_min, double fact_max, Func f)
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
399
400
  Distribution dist;
  dist.execDynamic(nwork, nthreads, chunksize_min, fact_max, move(f));
Martin Reinecke's avatar
Martin Reinecke committed
401
  }
Martin Reinecke's avatar
Martin Reinecke committed
402

Martin Reinecke's avatar
rework    
Martin Reinecke committed
403
404
405
406
407
408
409
template<typename Func> static void execParallel(size_t nthreads, Func f)
  {
  Distribution dist;
  dist.execParallel(nthreads, move(f));
  }

inline size_t max_threads()
Martin Reinecke's avatar
Martin Reinecke committed
410
  { return max_threads_; }
Martin Reinecke's avatar
rework    
Martin Reinecke committed
411
412
413

}

Martin Reinecke's avatar
Martin Reinecke committed
414
415
} // end of namespace detail

Martin Reinecke's avatar
Martin Reinecke committed
416
417
418
419
420
using detail_threading::Scheduler;
using detail_threading::execSingle;
using detail_threading::execStatic;
using detail_threading::execDynamic;
using detail_threading::execGuided;
Martin Reinecke's avatar
Martin Reinecke committed
421
422
using detail_threading::max_threads;
using detail_threading::execParallel;
Martin Reinecke's avatar
Martin Reinecke committed
423

Martin Reinecke's avatar
Martin Reinecke committed
424
425
426
} // end of namespace mr

#endif