thread_pool.cc 11.4 KB
Newer Older
Minjie Wang's avatar
Minjie Wang committed
1
2
3
4
5
6
/*!
 *  Copyright (c) 2017 by Contributors
 * \file thread_pool.cc
 * \brief Threadpool for multi-threading runtime.
 */
#include <dgl/runtime/c_backend_api.h>
7
#include <dgl/runtime/c_runtime_api.h>
Minjie Wang's avatar
Minjie Wang committed
8
#include <dgl/runtime/packed_func.h>
9
#include <dgl/runtime/registry.h>
Minjie Wang's avatar
Minjie Wang committed
10
11
#include <dgl/runtime/threading_backend.h>
#include <dmlc/logging.h>
12
13
#include <dmlc/thread_local.h>

Minjie Wang's avatar
Minjie Wang committed
14
#include <algorithm>
15
16
#include <atomic>
#include <condition_variable>
Minjie Wang's avatar
Minjie Wang committed
17
18
#include <cstring>
#include <memory>
19
#include <mutex>
Minjie Wang's avatar
Minjie Wang committed
20
#include <sstream>
21
22
23
#include <string>
#include <thread>
#include <vector>
Minjie Wang's avatar
Minjie Wang committed
24
25
26

const constexpr int kL1CacheBytes = 64;

27
namespace dgl {
Minjie Wang's avatar
Minjie Wang committed
28
29
30
31
32
33
34
35
36
37
38
namespace runtime {

// stride in the page, fit to cache line.
constexpr int kSyncStride = 64 / sizeof(std::atomic<int>);

/*!
 * \brief Thread local master environment.
 */
class ParallelLauncher {
 public:
  // Reset the the task request.
39
40
  void Init(
      FDGLParallelLambda flambda, void* cdata, int num_task, bool need_sync) {
Minjie Wang's avatar
Minjie Wang committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    num_pending_.store(num_task);
    this->cdata = cdata;
    this->flambda = flambda;
    this->env.num_task = num_task;
    has_error_.store(false);
    // reshape
    if (static_cast<size_t>(num_task) > par_errors_.size()) {
      par_errors_.resize(num_task + 1);
      if (need_sync) {
        delete[] sync_counter_;
        sync_counter_ = new std::atomic<int>[num_task * kSyncStride];
      }
    }
    if (need_sync) {
      for (int i = 0; i < num_task; ++i) {
56
        sync_counter_[i * kSyncStride].store(0, std::memory_order_relaxed);
Minjie Wang's avatar
Minjie Wang committed
57
58
59
60
61
62
      }
      this->env.sync_handle = sync_counter_;
    } else {
      this->env.sync_handle = nullptr;
    }
  }
63
  ~ParallelLauncher() { delete[] sync_counter_; }
Minjie Wang's avatar
Minjie Wang committed
64
65
66
  // Wait n jobs to finish
  int WaitForJobs() {
    while (num_pending_.load() != 0) {
67
      dgl::runtime::threading::YieldThread();
Minjie Wang's avatar
Minjie Wang committed
68
69
70
71
72
73
74
75
76
77
78
    }
    if (!has_error_.load()) return 0;
    // the following is intended to use string due to
    // security issue raised in SGX backend
    std::string err("");
    for (size_t i = 0; i < par_errors_.size(); ++i) {
      if (par_errors_[i].length() != 0) {
        err += "Task " + std::to_string(i) + " error: " + par_errors_[i] + '\n';
        par_errors_[i].clear();
      }
    }
79
    DGLAPISetLastError(err.c_str());
Minjie Wang's avatar
Minjie Wang committed
80
81
82
83
84
    return -1;
  }
  // Signal that one job has finished.
  void SignalJobError(int task_id) {
    num_pending_.fetch_sub(1);
85
    par_errors_[task_id] = DGLGetLastError();
Minjie Wang's avatar
Minjie Wang committed
86
87
88
    has_error_.store(true);
  }
  // Signal that one job has finished.
89
  void SignalJobFinish() { num_pending_.fetch_sub(1); }
Minjie Wang's avatar
Minjie Wang committed
90
91
92
93
94
  // Get thread local version of the store.
  static ParallelLauncher* ThreadLocal() {
    return dmlc::ThreadLocalStore<ParallelLauncher>::Get();
  }
  // The parallel lambda
95
  FDGLParallelLambda flambda;
Minjie Wang's avatar
Minjie Wang committed
96
97
98
  // The closure data
  void* cdata;
  // Local env
99
  DGLParallelGroupEnv env;
Minjie Wang's avatar
Minjie Wang committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
  // Whether this thread is worker of the pool.
  // used to prevent recursive launch.
  bool is_worker{false};

 private:
  // The pending jobs.
  std::atomic<int32_t> num_pending_;
  // Whether error has been countered.
  std::atomic<bool> has_error_;
  // The counter page.
  std::atomic<int32_t>* sync_counter_{nullptr};
  // The error message
  std::vector<std::string> par_errors_;
};

/*! \brief Lock-free single-producer-single-consumer queue for each thread */
class SpscTaskQueue {
 public:
  /*! \brief The task entry */
  struct Task {
    ParallelLauncher* launcher;
    int32_t task_id;
  };

124
  SpscTaskQueue() : buffer_(new Task[kRingSize]), head_(0), tail_(0) {}
Minjie Wang's avatar
Minjie Wang committed
125

126
  ~SpscTaskQueue() { delete[] buffer_; }
Minjie Wang's avatar
Minjie Wang committed
127
128
129
130
131
132
133

  /*!
   * \brief Push a task into the queue and notify the comsumer if it is on wait.
   * \param input The task to be dequeued.
   */
  void Push(const Task& input) {
    while (!Enqueue(input)) {
134
      dgl::runtime::threading::YieldThread();
Minjie Wang's avatar
Minjie Wang committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    }
    if (pending_.fetch_add(1) == -1) {
      std::unique_lock<std::mutex> lock(mutex_);
      cv_.notify_one();
    }
  }

  /*!
   * \brief Pop a task out of the queue and condition wait if no tasks.
   * \param output The pointer to the task to be dequeued.
   * \param spin_count The number of iterations to spin before sleep.
   * \return Whether pop is successful (true) or we need to exit now (false).
   */
  bool Pop(Task* output, uint32_t spin_count = 300000) {
    // Busy wait a bit when the queue is empty.
150
151
152
    // If a new task comes to the queue quickly, this wait avoid the worker from
    // sleeping. The default spin count is set by following the typical omp
    // convention
Minjie Wang's avatar
Minjie Wang committed
153
    for (uint32_t i = 0; i < spin_count && pending_.load() == 0; ++i) {
154
      dgl::runtime::threading::YieldThread();
Minjie Wang's avatar
Minjie Wang committed
155
156
157
    }
    if (pending_.fetch_sub(1) == 0) {
      std::unique_lock<std::mutex> lock(mutex_);
158
159
      cv_.wait(
          lock, [this] { return pending_.load() >= 0 || exit_now_.load(); });
Minjie Wang's avatar
Minjie Wang committed
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
    }
    if (exit_now_.load(std::memory_order_relaxed)) {
      return false;
    }
    const uint32_t head = head_.load(std::memory_order_relaxed);
    // sanity check if the queue is empty
    CHECK(tail_.load(std::memory_order_acquire) != head);
    *output = buffer_[head];
    head_.store((head + 1) % kRingSize, std::memory_order_release);
    return true;
  }

  /*!
   * \brief Signal to terminate the worker.
   */
  void SignalForKill() {
    std::lock_guard<std::mutex> lock(mutex_);
    exit_now_.store(true);
    cv_.notify_all();
  }

 protected:
  /*!
   * \brief Lock-free enqueue.
   * \param input The task to be enqueued.
   * \return Whether the task is enqueued.
   */
  bool Enqueue(const Task& input) {
    if (exit_now_.load(std::memory_order_relaxed)) return false;

    const uint32_t tail = tail_.load(std::memory_order_relaxed);

    if ((tail + 1) % kRingSize != (head_.load(std::memory_order_acquire))) {
      buffer_[tail] = input;
      tail_.store((tail + 1) % kRingSize, std::memory_order_release);
      return true;
    }
    return false;
  }

200
201
  // the cache line paddings are used for avoid false sharing between atomic
  // variables
Minjie Wang's avatar
Minjie Wang committed
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
  typedef char cache_line_pad_t[kL1CacheBytes];
  cache_line_pad_t pad0_;
  // size of the queue, the queue can host size_ - 1 items at most
  // define it as a constant for better compiler optimization
  static constexpr const int kRingSize = 2;
  // pointer to access the item
  Task* const buffer_;

  cache_line_pad_t pad1_;
  // queue head, where one gets a task from the queue
  std::atomic<uint32_t> head_;

  cache_line_pad_t pad2_;
  // queue tail, when one puts a task to the queue
  std::atomic<uint32_t> tail_;

  cache_line_pad_t pad3_;
  // pending tasks in the queue
  std::atomic<int8_t> pending_{0};

  cache_line_pad_t pad4_;
  // signal for exit now
  std::atomic<bool> exit_now_{false};

  // internal mutex
  std::mutex mutex_;
  // cv for consumer
  std::condition_variable cv_;
};

// The thread pool
class ThreadPool {
 public:
235
  ThreadPool() : num_workers_(dgl::runtime::threading::MaxConcurrency()) {
Minjie Wang's avatar
Minjie Wang committed
236
237
238
239
    for (int i = 0; i < num_workers_; ++i) {
      // The SpscTaskQueue only hosts ONE item at a time
      queues_.emplace_back(std::unique_ptr<SpscTaskQueue>(new SpscTaskQueue()));
    }
240
241
    threads_ = std::unique_ptr<dgl::runtime::threading::ThreadGroup>(
        new dgl::runtime::threading::ThreadGroup(
242
243
244
245
            num_workers_, [this](int worker_id) { this->RunWorker(worker_id); },
            exclude_worker0_ /* include_main_thread */));
    num_workers_used_ =
        threads_->Configure(threading::ThreadGroup::kBig, 0, exclude_worker0_);
Minjie Wang's avatar
Minjie Wang committed
246
247
248
249
250
251
252
  }
  ~ThreadPool() {
    for (std::unique_ptr<SpscTaskQueue>& q : queues_) {
      q->SignalForKill();
    }
    threads_.reset();
  }
253
254
  int Launch(
      FDGLParallelLambda flambda, void* cdata, int num_task, int need_sync) {
Minjie Wang's avatar
Minjie Wang committed
255
    ParallelLauncher* launcher = ParallelLauncher::ThreadLocal();
256
257
    CHECK(!launcher->is_worker) << "Cannot launch parallel job inside worker, "
                                   "consider fuse then parallel";
Minjie Wang's avatar
Minjie Wang committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    if (num_task == 0) {
      num_task = num_workers_used_;
    }
    if (need_sync != 0) {
      CHECK_LE(num_task, num_workers_used_)
          << "Request parallel sync task larger than number of threads used "
          << " workers=" << num_workers_used_ << " request=" << num_task;
    }
    launcher->Init(flambda, cdata, num_task, need_sync != 0);
    SpscTaskQueue::Task tsk;
    tsk.launcher = launcher;
    // if worker0 is taken by the master, queues_[0] is abandoned
    for (int i = exclude_worker0_; i < num_task; ++i) {
      tsk.task_id = i;
      queues_[i]->Push(tsk);
    }
    // use the master thread to run task 0
    if (exclude_worker0_) {
276
      DGLParallelGroupEnv* penv = &(tsk.launcher->env);
Minjie Wang's avatar
Minjie Wang committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
      if ((*tsk.launcher->flambda)(0, penv, cdata) == 0) {
        tsk.launcher->SignalJobFinish();
      } else {
        tsk.launcher->SignalJobError(tsk.task_id);
      }
    }
    int res = launcher->WaitForJobs();
    return res;
  }

  static ThreadPool* ThreadLocal() {
    return dmlc::ThreadLocalStore<ThreadPool>::Get();
  }

291
292
  void UpdateWorkerConfiguration(
      threading::ThreadGroup::AffinityMode mode, int nthreads) {
Minjie Wang's avatar
Minjie Wang committed
293
294
    // this will also reset the affinity of the ThreadGroup
    // may use less than the MaxConcurrency number of workers
295
    num_workers_used_ = threads_->Configure(mode, nthreads, exclude_worker0_);
Minjie Wang's avatar
Minjie Wang committed
296
297
298
299
300
301
302
303
304
305
306
307
308
    // if MaxConcurrency restricted the number of workers (e.g., due to
    // hyperthreading), respect the restriction
    num_workers_used_ = std::min(num_workers_, num_workers_used_);
  }

 private:
  // Internal worker function.
  void RunWorker(int worker_id) {
    SpscTaskQueue* queue = queues_[worker_id].get();
    SpscTaskQueue::Task task;
    ParallelLauncher::ThreadLocal()->is_worker = true;
    while (queue->Pop(&task)) {
      CHECK(task.launcher != nullptr);
309
      DGLParallelGroupEnv* penv = &(task.launcher->env);
Minjie Wang's avatar
Minjie Wang committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
      void* cdata = task.launcher->cdata;
      if ((*task.launcher->flambda)(task.task_id, penv, cdata) == 0) {
        task.launcher->SignalJobFinish();
      } else {
        task.launcher->SignalJobError(task.task_id);
      }
    }
  }
  int num_workers_;
  // number of workers used (can be restricted with affinity pref)
  int num_workers_used_;
  // if excluding worker 0 and using master to run task 0
#ifndef _LIBCPP_SGX_CONFIG
  bool exclude_worker0_{true};
#else
  bool exclude_worker0_{false};
#endif
  std::vector<std::unique_ptr<SpscTaskQueue> > queues_;
328
  std::unique_ptr<dgl::runtime::threading::ThreadGroup> threads_;
Minjie Wang's avatar
Minjie Wang committed
329
330
};

331
DGL_REGISTER_GLOBAL("runtime.config_threadpool")
332
333
334
335
336
337
338
    .set_body([](DGLArgs args, DGLRetValue* rv) {
      threading::ThreadGroup::AffinityMode mode =
          static_cast<threading::ThreadGroup::AffinityMode>(
              static_cast<int>(args[0]));
      int nthreads = args[1];
      ThreadPool::ThreadLocal()->UpdateWorkerConfiguration(mode, nthreads);
    });
Minjie Wang's avatar
Minjie Wang committed
339
340

}  // namespace runtime
341
}  // namespace dgl
Minjie Wang's avatar
Minjie Wang committed
342

343
int DGLBackendParallelLaunch(
344
    FDGLParallelLambda flambda, void* cdata, int num_task) {
345
  int res = dgl::runtime::ThreadPool::ThreadLocal()->Launch(
Minjie Wang's avatar
Minjie Wang committed
346
347
348
349
      flambda, cdata, num_task, 1);
  return res;
}

350
351
int DGLBackendParallelBarrier(int task_id, DGLParallelGroupEnv* penv) {
  using dgl::runtime::kSyncStride;
Minjie Wang's avatar
Minjie Wang committed
352
353
354
355
356
357
358
  int num_task = penv->num_task;
  std::atomic<int>* sync_counter =
      reinterpret_cast<std::atomic<int>*>(penv->sync_handle);
  int old_counter = sync_counter[task_id * kSyncStride].fetch_add(
      1, std::memory_order_release);
  for (int i = 0; i < num_task; ++i) {
    if (i != task_id) {
359
360
      while (sync_counter[i * kSyncStride].load(std::memory_order_relaxed) <=
             old_counter) {
361
        dgl::runtime::threading::YieldThread();
Minjie Wang's avatar
Minjie Wang committed
362
363
364
365
366
367
      }
    }
  }
  std::atomic_thread_fence(std::memory_order_acquire);
  return 0;
}