threading.cc 12.7 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
92

  public:
    void push(T val)
      {
      lock_t lock(mut_);
Peter Bell's avatar
Peter Bell committed
93
      ++size_;
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

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

Peter Bell's avatar
Peter Bell committed
110
    bool empty() const { return size_==0; }
Martin Reinecke's avatar
Martin Reinecke committed
111
112
113
114
  };

class thread_pool
  {
115
  private:
116
117
118
    // A reasonable guess, probably close enough for most hardware
    static constexpr size_t cache_line_size = 64;
    struct alignas(cache_line_size) worker
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

Peter Bell's avatar
Peter Bell committed
126
127
128
      void worker_main(
        std::atomic<bool> &shutdown_flag,
        std::atomic<size_t> &unscheduled_tasks,
129
130
131
        concurrent_queue<std::function<void()>> &overflow_work)
        {
        using lock_t = std::unique_lock<std::mutex>;
Peter Bell's avatar
Peter Bell committed
132
133
        bool expect_work = true;
        while (!shutdown_flag || expect_work)
134
          {
135
          std::function<void()> local_work;
Peter Bell's avatar
Peter Bell committed
136
137
138
139
140
141
142
143
          if (expect_work || unscheduled_tasks == 0)
            {
            lock_t lock(mut);
            // Wait until there is work to be executed
            work_ready.wait(lock, [&]{ return (work || shutdown_flag); });
            local_work.swap(work);
            expect_work = false;
            }
144

Peter Bell's avatar
Peter Bell committed
145
146
147
148
149
150
          bool marked_busy = false;
          if (local_work)
            {
            marked_busy = true;
            local_work();
            }
151

Peter Bell's avatar
Peter Bell committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
          if (!overflow_work.empty())
            {
            if (!marked_busy && busy_flag.test_and_set())
              {
              expect_work = true;
              continue;
              }
            marked_busy = true;

            while (overflow_work.try_pop(local_work))
              {
              --unscheduled_tasks;
              local_work();
              }
            }
167

Peter Bell's avatar
Peter Bell committed
168
          if (marked_busy) busy_flag.clear();
169
170
171
172
173
174
175
176
          }
        }
      };

    concurrent_queue<std::function<void()>> overflow_work_;
    std::mutex mut_;
    std::vector<worker> workers_;
    std::atomic<bool> shutdown_;
Peter Bell's avatar
Peter Bell committed
177
    std::atomic<size_t> unscheduled_tasks_;
178
    using lock_t = std::lock_guard<std::mutex>;
Martin Reinecke's avatar
Martin Reinecke committed
179
180
181

    void create_threads()
      {
182
183
      lock_t lock(mut_);
      size_t nthreads=workers_.size();
Martin Reinecke's avatar
Martin Reinecke committed
184
185
      for (size_t i=0; i<nthreads; ++i)
        {
186
187
188
189
190
191
        try
          {
          auto *worker = &workers_[i];
          worker->busy_flag.clear();
          worker->work = nullptr;
          worker->thread = std::thread(
Peter Bell's avatar
Peter Bell committed
192
            [worker, this]{ worker->worker_main(shutdown_, unscheduled_tasks_, overflow_work_); });
193
          }
Martin Reinecke's avatar
Martin Reinecke committed
194
195
        catch (...)
          {
196
          shutdown_locked();
Martin Reinecke's avatar
Martin Reinecke committed
197
198
199
200
201
          throw;
          }
        }
      }

202
203
204
205
206
207
208
209
210
211
212
    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
213
214
  public:
    explicit thread_pool(size_t nthreads):
215
      workers_(nthreads)
Martin Reinecke's avatar
Martin Reinecke committed
216
217
      { create_threads(); }

218
    thread_pool(): thread_pool(max_threads_) {}
Martin Reinecke's avatar
Martin Reinecke committed
219

220
    ~thread_pool() { shutdown(); }
Martin Reinecke's avatar
Martin Reinecke committed
221

Martin Reinecke's avatar
Martin Reinecke committed
222
223
    void submit(std::function<void()> work)
      {
224
225
226
227
      lock_t lock(mut_);
      if (shutdown_)
        throw std::runtime_error("Work item submitted after shutdown");

Peter Bell's avatar
Peter Bell committed
228
      ++unscheduled_tasks_;
229
230

      // First check for any idle workers and wake those
Peter Bell's avatar
Peter Bell committed
231
232
233
234
235
236
237
238
239
240
241
242
      for (auto &worker : workers_)
        if (!worker.busy_flag.test_and_set())
          {
          --unscheduled_tasks_;
          {
          lock_t lock(worker.mut);
          worker.work = std::move(work);
          }
          worker.work_ready.notify_one();
          return;
          }

243
244
      // If no workers were idle, push onto the overflow queue for later
      overflow_work_.push(std::move(work));
Martin Reinecke's avatar
Martin Reinecke committed
245
246
247
248
      }

    void shutdown()
      {
249
250
      lock_t lock(mut_);
      shutdown_locked();
Martin Reinecke's avatar
Martin Reinecke committed
251
252
253
254
      }

    void restart()
      {
255
      shutdown_ = false;
Martin Reinecke's avatar
Martin Reinecke committed
256
257
258
259
      create_threads();
      }
  };

260
inline thread_pool &get_pool()
Martin Reinecke's avatar
Martin Reinecke committed
261
  {
262
  static thread_pool pool;
Martin Reinecke's avatar
Martin Reinecke committed
263
264
265
266
267
268
269
270
271
272
273
274
#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

275
  return pool;
Martin Reinecke's avatar
Martin Reinecke committed
276
  }
Martin Reinecke's avatar
Martin Reinecke committed
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

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
305
306
    void execStatic(size_t nwork, size_t nthreads, size_t chunksize,
      std::function<void(Scheduler &)> f)
Martin Reinecke's avatar
Martin Reinecke committed
307
308
309
310
311
312
313
314
315
316
317
318
      {
      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
319
320
    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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
      {
      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
363
          size_t tmp = size_t((fact_max_*double(rem))/double(nthreads_));
Martin Reinecke's avatar
Martin Reinecke committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
          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
391
392
393
394
395
396
397
  if (nthreads_ == 1)
    {
    MyScheduler sched(*this, 0);
    f(sched);
    return;
    }

398
  auto & pool = get_pool();
Martin Reinecke's avatar
Martin Reinecke committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
  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
421
    std::rethrow_exception(ex);
Martin Reinecke's avatar
Martin Reinecke committed
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
  }

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
481
482
void execStatic(size_t nwork, size_t, size_t,
  std::function<void(Scheduler &)> func)
Martin Reinecke's avatar
Martin Reinecke committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
  {
  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

}}