threading.h 10.4 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
/*
 *  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
 */

19
/* Copyright (C) 2019-2020 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
inline atomic<size_t> &default_nthreads()
  {
  static atomic<size_t> default_nthreads_=max_threads_;
  return default_nthreads_;
  }

inline size_t get_default_nthreads()
  { return default_nthreads(); }

inline void set_default_nthreads(size_t new_default_nthreads)
  { default_nthreads() = max<size_t>(1, new_default_nthreads); }

Martin Reinecke's avatar
Martin Reinecke committed
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
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
163
    thread_pool(): thread_pool(max_threads_) {}
Martin Reinecke's avatar
Martin Reinecke committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186

    ~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
187
inline thread_pool &get_pool()
Martin Reinecke's avatar
Martin Reinecke committed
188
189
  {
  static thread_pool pool;
Martin Reinecke's avatar
Martin Reinecke committed
190
#if __has_include(<pthread.h>)
Martin Reinecke's avatar
Martin Reinecke committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
  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
205
struct Range
Martin Reinecke's avatar
Martin Reinecke committed
206
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
207
208
209
210
211
  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
212

Martin Reinecke's avatar
rework    
Martin Reinecke committed
213
class Distribution
Martin Reinecke's avatar
Martin Reinecke committed
214
215
216
217
218
219
220
221
222
  {
  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
223
    enum SchedMode { SINGLE, STATIC, DYNAMIC };
Martin Reinecke's avatar
Martin Reinecke committed
224
225
    SchedMode mode;
    bool single_done;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
226
227

    template <typename Func> void thread_map(Func f);
Martin Reinecke's avatar
Martin Reinecke committed
228
229
230
231
232
233
234
235
236

  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
237
238
      nthreads_ = 1;
      thread_map(move(f));
Martin Reinecke's avatar
Martin Reinecke committed
239
240
241
242
243
      }
    template<typename Func> void execStatic(size_t nwork,
      size_t nthreads, size_t chunksize, Func f)
      {
      mode = STATIC;
244
      nthreads_ = (nthreads==0) ? get_default_nthreads() : nthreads;
Martin Reinecke's avatar
Martin Reinecke committed
245
246
247
248
249
250
251
      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
252
      thread_map(move(f));
Martin Reinecke's avatar
Martin Reinecke committed
253
254
255
256
257
      }
    template<typename Func> void execDynamic(size_t nwork,
      size_t nthreads, size_t chunksize_min, double fact_max, Func f)
      {
      mode = DYNAMIC;
258
      nthreads_ = (nthreads==0) ? get_default_nthreads() : nthreads;
Martin Reinecke's avatar
Martin Reinecke committed
259
260
261
262
263
264
      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
265
      thread_map(move(f));
Martin Reinecke's avatar
Martin Reinecke committed
266
      }
Martin Reinecke's avatar
rework    
Martin Reinecke committed
267
268
269
    template<typename Func> void execParallel(size_t nthreads, Func f)
      {
      mode = STATIC;
270
      nthreads_ = (nthreads==0) ? get_default_nthreads() : nthreads;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
271
272
273
274
275
      nwork_ = nthreads_;
      chunksize_ = 1;
      thread_map(move(f));
      }
    Range getNext(size_t thread_id)
Martin Reinecke's avatar
Martin Reinecke committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
      {
      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
310
class Scheduler
Martin Reinecke's avatar
Martin Reinecke committed
311
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
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
338
339
340
341
342
343
344
345
346
347
348
349
  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
350
351
352
353
354
355
  }

#else

constexpr size_t max_threads_ = 1;

Martin Reinecke's avatar
rework    
Martin Reinecke committed
356
class Sched0
Martin Reinecke's avatar
Martin Reinecke committed
357
358
359
360
361
362
363
364
365
366
  {
  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
367
      f(Scheduler(*this,0));
Martin Reinecke's avatar
Martin Reinecke committed
368
369
370
371
372
373
374
375
376
377
      }
    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
378
      Range res(0, nwork_);
Martin Reinecke's avatar
Martin Reinecke committed
379
      nwork_=0;
Martin Reinecke's avatar
rework    
Martin Reinecke committed
380
      return res;
Martin Reinecke's avatar
Martin Reinecke committed
381
382
383
384
385
386
      }
  };

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

387
388
389
390
391
392
inline size_t get_default_nthreads()
  { return 1; }

inline void set_default_nthreads(size_t /*new_default_nthreads*/)
  {}

Martin Reinecke's avatar
Martin Reinecke committed
393
394
#endif

Martin Reinecke's avatar
rework    
Martin Reinecke committed
395
396
namespace {

Martin Reinecke's avatar
Martin Reinecke committed
397
398
template<typename Func> void execSingle(size_t nwork, Func f)
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
399
400
  Distribution dist;
  dist.execSingle(nwork, move(f));
Martin Reinecke's avatar
Martin Reinecke committed
401
402
403
404
  }
template<typename Func> void execStatic(size_t nwork,
  size_t nthreads, size_t chunksize, Func f)
  {
Martin Reinecke's avatar
rework    
Martin Reinecke committed
405
406
  Distribution dist;
  dist.execStatic(nwork, nthreads, chunksize, move(f));
Martin Reinecke's avatar
Martin Reinecke committed
407
408
409
410
  }
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
411
412
  Distribution dist;
  dist.execDynamic(nwork, nthreads, chunksize_min, 0., move(f));
Martin Reinecke's avatar
Martin Reinecke committed
413
414
415
416
  }
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
417
418
  Distribution dist;
  dist.execDynamic(nwork, nthreads, chunksize_min, fact_max, move(f));
Martin Reinecke's avatar
Martin Reinecke committed
419
  }
Martin Reinecke's avatar
Martin Reinecke committed
420

Martin Reinecke's avatar
rework    
Martin Reinecke committed
421
422
423
424
425
426
427
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
428
  { return max_threads_; }
Martin Reinecke's avatar
rework    
Martin Reinecke committed
429
430
431

}

Martin Reinecke's avatar
Martin Reinecke committed
432
433
} // end of namespace detail

434
435
using detail_threading::get_default_nthreads;
using detail_threading::set_default_nthreads;
Martin Reinecke's avatar
Martin Reinecke committed
436
437
438
439
440
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
441
442
using detail_threading::max_threads;
using detail_threading::execParallel;
Martin Reinecke's avatar
Martin Reinecke committed
443

Martin Reinecke's avatar
Martin Reinecke committed
444
445
446
} // end of namespace mr

#endif