threading.cc 12.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
19
20
21
/*
 *  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-2020 Peter Bell, Max-Planck-Society
   Authors: Peter Bell, Martin Reinecke */

Martin Reinecke's avatar
Martin Reinecke committed
22
#include "ducc0/infra/threading.h"
Martin Reinecke's avatar
Martin Reinecke committed
23

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

Martin Reinecke's avatar
Martin Reinecke committed
38
namespace ducc0 {
Martin Reinecke's avatar
Martin Reinecke committed
39
40
41

namespace detail_threading {

Martin Reinecke's avatar
Martin Reinecke committed
42
#ifndef DUCC0_NO_THREADING
Martin Reinecke's avatar
Martin Reinecke committed
43

44
45
46
static const size_t max_threads_ = std::max<size_t>(1, std::thread::hardware_concurrency());

std::atomic<size_t> default_nthreads_(max_threads_);
Martin Reinecke's avatar
Martin Reinecke committed
47
48
49
50
51
52
53

size_t get_default_nthreads()
  { return default_nthreads_; }

void set_default_nthreads(size_t new_default_nthreads)
  { default_nthreads_ = std::max<size_t>(1, new_default_nthreads); }

54
55
size_t max_threads() { return max_threads_; }

Martin Reinecke's avatar
Martin Reinecke committed
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
class latch
  {
    std::atomic<size_t> num_left_;
    std::mutex mut_;
    std::condition_variable completed_;
    using lock_t = std::unique_lock<std::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
  {
    std::queue<T> q_;
    std::mutex mut_;
86
87
    std::atomic<size_t> size_;
    using lock_t = std::lock_guard<std::mutex>;
Martin Reinecke's avatar
Martin Reinecke committed
88
89
90
91

  public:
    void push(T val)
      {
92
      ++size_;
Martin Reinecke's avatar
Martin Reinecke committed
93
      lock_t lock(mut_);
94
      q_.push(std::move(val));
Martin Reinecke's avatar
Martin Reinecke committed
95
96
      }

97
    bool try_pop(T &val)
Martin Reinecke's avatar
Martin Reinecke committed
98
      {
99
      if (size_==0) return false;
Martin Reinecke's avatar
Martin Reinecke committed
100
      lock_t lock(mut_);
101
102
      // Queue might have been emptied while we acquired the lock
      if (q_.empty()) return false;
Martin Reinecke's avatar
Martin Reinecke committed
103

104
      --size_;
Martin Reinecke's avatar
Martin Reinecke committed
105
106
107
108
109
110
111
112
      val = std::move(q_.front());
      q_.pop();
      return true;
      }
  };

class thread_pool
  {
113
114
115
116
117
118
  private:
#if __cpp_lib_hardware_interference_size >= 201603
    struct alignas(std::hardware_destructive_interference_size) worker
#else
    struct alignas(64) worker
#endif
Martin Reinecke's avatar
Martin Reinecke committed
119
      {
120
121
122
123
      std::thread thread;
      std::condition_variable work_ready;
      std::mutex mut;
      std::atomic_flag busy_flag = ATOMIC_FLAG_INIT;
Martin Reinecke's avatar
Martin Reinecke committed
124
      std::function<void()> work;
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

      void worker_main(std::atomic<bool> & shutdown_flag,
        concurrent_queue<std::function<void()>> &overflow_work)
        {
        using lock_t = std::unique_lock<std::mutex>;
        lock_t lock(mut);
        while (!shutdown_flag)
          {
          // Wait to be woken by the thread pool with a piece of work
          work_ready.wait(lock, [&]{ return (work || shutdown_flag); });
          if (!work) continue;
          work();

          // Execute any work which queued up while we were busy
          while (overflow_work.try_pop(work)) work();

          // Mark ourself as available before going back to sleep
          work = nullptr;
          busy_flag.clear();
          }
        }
      };

    concurrent_queue<std::function<void()>> overflow_work_;
    std::mutex mut_;
    std::vector<worker> workers_;
    std::atomic<bool> shutdown_;
    using lock_t = std::lock_guard<std::mutex>;
Martin Reinecke's avatar
Martin Reinecke committed
153
154
155

    void create_threads()
      {
156
157
      lock_t lock(mut_);
      size_t nthreads=workers_.size();
Martin Reinecke's avatar
Martin Reinecke committed
158
159
      for (size_t i=0; i<nthreads; ++i)
        {
160
161
162
163
164
165
166
167
        try
          {
          auto *worker = &workers_[i];
          worker->busy_flag.clear();
          worker->work = nullptr;
          worker->thread = std::thread(
            [worker, this]{ worker->worker_main(shutdown_, overflow_work_); });
          }
Martin Reinecke's avatar
Martin Reinecke committed
168
169
        catch (...)
          {
170
          shutdown_locked();
Martin Reinecke's avatar
Martin Reinecke committed
171
172
173
174
175
          throw;
          }
        }
      }

176
177
178
179
180
181
182
183
184
185
186
    void shutdown_locked()
      {
      shutdown_ = true;
      for (auto &worker : workers_)
        worker.work_ready.notify_all();

      for (auto &worker : workers_)
        if (worker.thread.joinable())
          worker.thread.join();
      }

Martin Reinecke's avatar
Martin Reinecke committed
187
188
  public:
    explicit thread_pool(size_t nthreads):
189
      workers_(nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
190
191
      { create_threads(); }

192
    thread_pool(): thread_pool(max_threads_) {}
Martin Reinecke's avatar
Martin Reinecke committed
193

194
    ~thread_pool() { shutdown(); }
Martin Reinecke's avatar
Martin Reinecke committed
195

Martin Reinecke's avatar
Martin Reinecke committed
196
197
    void submit(std::function<void()> work)
      {
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
      lock_t lock(mut_);
      if (shutdown_)
        throw std::runtime_error("Work item submitted after shutdown");

      auto submit_to_idle = [&](std::function<void()> &work) -> bool
        {
        for (auto &worker : workers_)
          if (!worker.busy_flag.test_and_set())
            {
            {
            lock_t lock(worker.mut);
            worker.work = std::move(work);
            }
            worker.work_ready.notify_one();
            return true;
            }
        return false;
        };

      // First check for any idle workers and wake those
      if (submit_to_idle(work)) return;
      // If no workers were idle, push onto the overflow queue for later
      overflow_work_.push(std::move(work));

      // Possible race: All workers might have gone idle between the first
      // submit attempt and pushing the work item into the queue. So, there
      // could be no active workers to check the queue.
      // Resolve with another check for idle workers.
      std::function<void()> dummy_work = []{};
      submit_to_idle(dummy_work);
Martin Reinecke's avatar
Martin Reinecke committed
228
229
230
231
      }

    void shutdown()
      {
232
233
      lock_t lock(mut_);
      shutdown_locked();
Martin Reinecke's avatar
Martin Reinecke committed
234
235
236
237
      }

    void restart()
      {
238
      shutdown_ = false;
Martin Reinecke's avatar
Martin Reinecke committed
239
240
241
242
      create_threads();
      }
  };

243
inline thread_pool &get_pool()
Martin Reinecke's avatar
Martin Reinecke committed
244
  {
245
  static thread_pool pool;
Martin Reinecke's avatar
Martin Reinecke committed
246
247
248
249
250
251
252
253
254
255
256
257
#if __has_include(<pthread.h>)
  static std::once_flag f;
  call_once(f,
    []{
    pthread_atfork(
      +[]{ get_pool().shutdown(); },  // prepare
      +[]{ get_pool().restart(); },   // parent
      +[]{ get_pool().restart(); }    // child
      );
    });
#endif

258
  return pool;
Martin Reinecke's avatar
Martin Reinecke committed
259
  }
Martin Reinecke's avatar
Martin Reinecke committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

class Distribution
  {
  private:
    size_t nthreads_;
    std::mutex mut_;
    size_t nwork_;
    size_t cur_;
    size_t chunksize_;
    double fact_max_;
    std::vector<size_t> nextstart;
    enum SchedMode { SINGLE, STATIC, DYNAMIC };
    SchedMode mode;
    bool single_done;

    void thread_map(std::function<void(Scheduler &)> f);

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

    void execSingle(size_t nwork, std::function<void(Scheduler &)> f)
      {
      mode = SINGLE;
      single_done = false;
      nwork_ = nwork;
      nthreads_ = 1;
      thread_map(move(f));
      }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
288
289
    void execStatic(size_t nwork, size_t nthreads, size_t chunksize,
      std::function<void(Scheduler &)> f)
Martin Reinecke's avatar
Martin Reinecke committed
290
291
292
293
294
295
296
297
298
299
300
301
      {
      mode = STATIC;
      nthreads_ = (nthreads==0) ? get_default_nthreads() : nthreads;
      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_;
      thread_map(move(f));
      }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
302
303
    void execDynamic(size_t nwork, size_t nthreads, size_t chunksize_min,
      double fact_max, std::function<void(Scheduler &)> f)
Martin Reinecke's avatar
Martin Reinecke committed
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
338
339
340
341
342
343
344
345
      {
      mode = DYNAMIC;
      nthreads_ = (nthreads==0) ? get_default_nthreads() : nthreads;
      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;
      thread_map(move(f));
      }
    void execParallel(size_t nthreads, std::function<void(Scheduler &)> f)
      {
      mode = STATIC;
      nthreads_ = (nthreads==0) ? get_default_nthreads() : nthreads;
      nwork_ = nthreads_;
      chunksize_ = 1;
      thread_map(move(f));
      }
    Range getNext(size_t thread_id)
      {
      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=std::min(lo+chunksize_,nwork_);
          nextstart[thread_id] += nthreads_*chunksize_;
          return Range(lo, hi);
          }
        case DYNAMIC:
          {
          std::unique_lock<std::mutex> lck(mut_);
          if (cur_>=nwork_) return Range();
          auto rem = nwork_-cur_;
Martin Reinecke's avatar
Martin Reinecke committed
346
          size_t tmp = size_t((fact_max_*double(rem))/double(nthreads_));
Martin Reinecke's avatar
Martin Reinecke committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
          auto sz = std::min(rem, std::max(chunksize_, tmp));
          size_t lo=cur_;
          cur_+=sz;
          size_t hi=cur_;
          return Range(lo, hi);
          }
        }
      return Range();
      }
  };

class MyScheduler: public Scheduler
  {
  private:
    Distribution &dist_;
    size_t ithread_;

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

void Distribution::thread_map(std::function<void(Scheduler &)> f)
  {
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
374
375
376
377
378
379
380
  if (nthreads_ == 1)
    {
    MyScheduler sched(*this, 0);
    f(sched);
    return;
    }

381
  auto & pool = get_pool();
Martin Reinecke's avatar
Martin Reinecke committed
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
  latch counter(nthreads_);
  std::exception_ptr ex;
  std::mutex ex_mut;
  for (size_t i=0; i<nthreads_; ++i)
    {
    pool.submit(
      [this, &f, i, &counter, &ex, &ex_mut] {
      try
        {
        MyScheduler sched(*this, i);
        f(sched);
        }
      catch (...)
        {
        std::lock_guard<std::mutex> lock(ex_mut);
        ex = std::current_exception();
        }
      counter.count_down();
      });
    }
  counter.wait();
  if (ex)
Martin Reinecke's avatar
fix    
Martin Reinecke committed
404
    std::rethrow_exception(ex);
Martin Reinecke's avatar
Martin Reinecke committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
  }

void execSingle(size_t nwork, std::function<void(Scheduler &)> func)
  {
  Distribution dist;
  dist.execSingle(nwork, move(func));
  }
void execStatic(size_t nwork, size_t nthreads, size_t chunksize,
  std::function<void(Scheduler &)> func)
  {
  Distribution dist;
  dist.execStatic(nwork, nthreads, chunksize, move(func));
  }
void execDynamic(size_t nwork, size_t nthreads, size_t chunksize_min,
  std::function<void(Scheduler &)> func)
  {
  Distribution dist;
  dist.execDynamic(nwork, nthreads, chunksize_min, 0., move(func));
  }
void execGuided(size_t nwork, size_t nthreads, size_t chunksize_min,
  double fact_max, std::function<void(Scheduler &)> func)
  {
  Distribution dist;
  dist.execDynamic(nwork, nthreads, chunksize_min, fact_max, move(func));
  }
void execParallel(size_t nthreads, std::function<void(Scheduler &)> func)
  {
  Distribution dist;
  dist.execParallel(nthreads, move(func));
  }

#else

size_t get_default_nthreads() { return 1; }
void set_default_nthreads(size_t /* new_default_nthreads */) {}
size_t max_threads() { return 1; }

class MyScheduler: public Scheduler
  {
  private:
    size_t nwork_;

  public:
    MyScheduler(size_t nwork) : nwork_(nwork) {}
    virtual size_t num_threads() const { return 1; }
    virtual size_t thread_num() const { return 0; }
    virtual Range getNext()
      {
      Range res(0, nwork_);
      nwork_=0;
      return res;
      }
  };

void execSingle(size_t nwork, std::function<void(Scheduler &)> func)
  {
  MyScheduler sched(nwork);
  func(sched);
  }
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
464
465
void execStatic(size_t nwork, size_t, size_t,
  std::function<void(Scheduler &)> func)
Martin Reinecke's avatar
Martin Reinecke committed
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
  {
  MyScheduler sched(nwork);
  func(sched);
  }
void execDynamic(size_t nwork, size_t, size_t,
  std::function<void(Scheduler &)> func)
  {
  MyScheduler sched(nwork);
  func(sched);
  }
void execGuided(size_t nwork, size_t, size_t, double,
  std::function<void(Scheduler &)> func)
  {
  MyScheduler sched(nwork);
  func(sched);
  }
void execParallel(size_t, std::function<void(Scheduler &)> func)
  {
  MyScheduler sched(1);
  func(sched);
  }

#endif

}}