NonBlockingThreadPool.h
Go to the documentation of this file.
1 // This file is part of Eigen, a lightweight C++ template library
2 // for linear algebra.
3 //
4 // Copyright (C) 2016 Dmitry Vyukov <dvyukov@google.com>
5 //
6 // This Source Code Form is subject to the terms of the Mozilla
7 // Public License v. 2.0. If a copy of the MPL was not distributed
8 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 
10 #ifndef EIGEN_CXX11_THREADPOOL_NONBLOCKING_THREAD_POOL_H
11 #define EIGEN_CXX11_THREADPOOL_NONBLOCKING_THREAD_POOL_H
12 
13 #include "./InternalHeaderCheck.h"
14 
15 namespace Eigen {
16 
17 template <typename Environment>
19  public:
20  typedef typename Environment::Task Task;
22 
23  ThreadPoolTempl(int num_threads, Environment env = Environment())
24  : ThreadPoolTempl(num_threads, true, env) {}
25 
26  ThreadPoolTempl(int num_threads, bool allow_spinning,
27  Environment env = Environment())
28  : env_(env),
29  num_threads_(num_threads),
30  allow_spinning_(allow_spinning),
31  thread_data_(num_threads),
32  all_coprimes_(num_threads),
33  waiters_(num_threads),
35  blocked_(0),
36  spinning_(0),
37  done_(false),
38  cancelled_(false),
39  ec_(waiters_) {
40  waiters_.resize(num_threads_);
41  // Calculate coprimes of all numbers [1, num_threads].
42  // Coprimes are used for random walks over all threads in Steal
43  // and NonEmptyQueueIndex. Iteration is based on the fact that if we take
44  // a random starting thread index t and calculate num_threads - 1 subsequent
45  // indices as (t + coprime) % num_threads, we will cover all threads without
46  // repetitions (effectively getting a presudo-random permutation of thread
47  // indices).
49  for (int i = 1; i <= num_threads_; ++i) {
50  all_coprimes_.emplace_back(i);
52  }
53 #ifndef EIGEN_THREAD_LOCAL
55 #endif
56  thread_data_.resize(num_threads_);
57  for (int i = 0; i < num_threads_; i++) {
59  thread_data_[i].thread.reset(
60  env_.CreateThread([this, i]() { WorkerLoop(i); }));
61  }
62 #ifndef EIGEN_THREAD_LOCAL
63  // Wait for workers to initialize per_thread_map_. Otherwise we might race
64  // with them in Schedule or CurrentThreadId.
65  init_barrier_->Wait();
66 #endif
67  }
68 
70  done_ = true;
71 
72  // Now if all threads block without work, they will start exiting.
73  // But note that threads can continue to work arbitrary long,
74  // block, submit new work, unblock and otherwise live full life.
75  if (!cancelled_) {
76  ec_.Notify(true);
77  } else {
78  // Since we were cancelled, there might be entries in the queues.
79  // Empty them to prevent their destructor from asserting.
80  for (size_t i = 0; i < thread_data_.size(); i++) {
81  thread_data_[i].queue.Flush();
82  }
83  }
84  // Join threads explicitly (by destroying) to avoid destruction order within
85  // this class.
86  for (size_t i = 0; i < thread_data_.size(); ++i)
87  thread_data_[i].thread.reset();
88  }
89 
90  void SetStealPartitions(const std::vector<std::pair<unsigned, unsigned>>& partitions) {
91  eigen_plain_assert(partitions.size() == static_cast<std::size_t>(num_threads_));
92 
93  // Pass this information to each thread queue.
94  for (int i = 0; i < num_threads_; i++) {
95  const auto& pair = partitions[i];
96  unsigned start = pair.first, end = pair.second;
97  AssertBounds(start, end);
98  unsigned val = EncodePartition(start, end);
99  SetStealPartition(i, val);
100  }
101  }
102 
103  void Schedule(std::function<void()> fn) EIGEN_OVERRIDE {
104  ScheduleWithHint(std::move(fn), 0, num_threads_);
105  }
106 
107  void ScheduleWithHint(std::function<void()> fn, int start,
108  int limit) override {
109  Task t = env_.CreateTask(std::move(fn));
110  PerThread* pt = GetPerThread();
111  if (pt->pool == this) {
112  // Worker thread of this pool, push onto the thread's queue.
113  Queue& q = thread_data_[pt->thread_id].queue;
114  t = q.PushFront(std::move(t));
115  } else {
116  // A free-standing thread (or worker of another pool), push onto a random
117  // queue.
118  eigen_plain_assert(start < limit);
120  int num_queues = limit - start;
121  int rnd = Rand(&pt->rand) % num_queues;
122  eigen_plain_assert(start + rnd < limit);
123  Queue& q = thread_data_[start + rnd].queue;
124  t = q.PushBack(std::move(t));
125  }
126  // Note: below we touch this after making w available to worker threads.
127  // Strictly speaking, this can lead to a racy-use-after-free. Consider that
128  // Schedule is called from a thread that is neither main thread nor a worker
129  // thread of this pool. Then, execution of w directly or indirectly
130  // completes overall computations, which in turn leads to destruction of
131  // this. We expect that such scenario is prevented by program, that is,
132  // this is kept alive while any threads can potentially be in Schedule.
133  if (!t.f) {
134  ec_.Notify(false);
135  } else {
136  env_.ExecuteTask(t); // Push failed, execute directly.
137  }
138  }
139 
141  cancelled_ = true;
142  done_ = true;
143 
144  // Let each thread know it's been cancelled.
145 #ifdef EIGEN_THREAD_ENV_SUPPORTS_CANCELLATION
146  for (size_t i = 0; i < thread_data_.size(); i++) {
147  thread_data_[i].thread->OnCancel();
148  }
149 #endif
150 
151  // Wake up the threads without work to let them exit on their own.
152  ec_.Notify(true);
153  }
154 
155  int NumThreads() const EIGEN_FINAL { return num_threads_; }
156 
158  const PerThread* pt = const_cast<ThreadPoolTempl*>(this)->GetPerThread();
159  if (pt->pool == this) {
160  return pt->thread_id;
161  } else {
162  return -1;
163  }
164  }
165 
166  private:
167  // Create a single atomic<int> that encodes start and limit information for
168  // each thread.
169  // We expect num_threads_ < 65536, so we can store them in a single
170  // std::atomic<unsigned>.
171  // Exposed publicly as static functions so that external callers can reuse
172  // this encode/decode logic for maintaining their own thread-safe copies of
173  // scheduling and steal domain(s).
174  static const int kMaxPartitionBits = 16;
175  static const int kMaxThreads = 1 << kMaxPartitionBits;
176 
177  inline unsigned EncodePartition(unsigned start, unsigned limit) {
178  return (start << kMaxPartitionBits) | limit;
179  }
180 
181  inline void DecodePartition(unsigned val, unsigned* start, unsigned* limit) {
182  *limit = val & (kMaxThreads - 1);
183  val >>= kMaxPartitionBits;
184  *start = val;
185  }
186 
187  void AssertBounds(int start, int end) {
188  eigen_plain_assert(start >= 0);
189  eigen_plain_assert(start < end); // non-zero sized partition
191  }
192 
193  inline void SetStealPartition(size_t i, unsigned val) {
194  thread_data_[i].steal_partition.store(val, std::memory_order_relaxed);
195  }
196 
197  inline unsigned GetStealPartition(int i) {
198  return thread_data_[i].steal_partition.load(std::memory_order_relaxed);
199  }
200 
201  void ComputeCoprimes(int N, MaxSizeVector<unsigned>* coprimes) {
202  for (int i = 1; i <= N; i++) {
203  unsigned a = i;
204  unsigned b = N;
205  // If GCD(a, b) == 1, then a and b are coprimes.
206  while (b != 0) {
207  unsigned tmp = a;
208  a = b;
209  b = tmp % b;
210  }
211  if (a == 1) {
212  coprimes->push_back(i);
213  }
214  }
215  }
216 
217  typedef typename Environment::EnvThread Thread;
218 
219  struct PerThread {
220  constexpr PerThread() : pool(NULL), rand(0), thread_id(-1) {}
221  ThreadPoolTempl* pool; // Parent pool, or null for normal threads.
222  uint64_t rand; // Random generator state.
223  int thread_id; // Worker thread index in pool.
224 #ifndef EIGEN_THREAD_LOCAL
225  // Prevent false sharing.
226  char pad_[128];
227 #endif
228  };
229 
230  struct ThreadData {
231  constexpr ThreadData() : thread(), steal_partition(0), queue() {}
232  std::unique_ptr<Thread> thread;
233  std::atomic<unsigned> steal_partition;
235  };
236 
237  Environment env_;
238  const int num_threads_;
239  const bool allow_spinning_;
244  std::atomic<unsigned> blocked_;
245  std::atomic<bool> spinning_;
246  std::atomic<bool> done_;
247  std::atomic<bool> cancelled_;
249 #ifndef EIGEN_THREAD_LOCAL
250  std::unique_ptr<Barrier> init_barrier_;
251  EIGEN_MUTEX per_thread_map_mutex_; // Protects per_thread_map_.
252  std::unordered_map<uint64_t, std::unique_ptr<PerThread>> per_thread_map_;
253 #endif
254 
255  // Main worker thread loop.
256  void WorkerLoop(int thread_id) {
257 #ifndef EIGEN_THREAD_LOCAL
258  std::unique_ptr<PerThread> new_pt(new PerThread());
259  per_thread_map_mutex_.lock();
260  bool insertOK = per_thread_map_.emplace(GlobalThreadIdHash(), std::move(new_pt)).second;
261  eigen_plain_assert(insertOK);
262  EIGEN_UNUSED_VARIABLE(insertOK);
263  per_thread_map_mutex_.unlock();
264  init_barrier_->Notify();
265  init_barrier_->Wait();
266 #endif
267  PerThread* pt = GetPerThread();
268  pt->pool = this;
269  pt->rand = GlobalThreadIdHash();
270  pt->thread_id = thread_id;
271  Queue& q = thread_data_[thread_id].queue;
272  EventCount::Waiter* waiter = &waiters_[thread_id];
273  // TODO(dvyukov,rmlarsen): The time spent in NonEmptyQueueIndex() is
274  // proportional to num_threads_ and we assume that new work is scheduled at
275  // a constant rate, so we set spin_count to 5000 / num_threads_. The
276  // constant was picked based on a fair dice roll, tune it.
277  const int spin_count =
278  allow_spinning_ && num_threads_ > 0 ? 5000 / num_threads_ : 0;
279  if (num_threads_ == 1) {
280  // For num_threads_ == 1 there is no point in going through the expensive
281  // steal loop. Moreover, since NonEmptyQueueIndex() calls PopBack() on the
282  // victim queues it might reverse the order in which ops are executed
283  // compared to the order in which they are scheduled, which tends to be
284  // counter-productive for the types of I/O workloads the single thread
285  // pools tend to be used for.
286  while (!cancelled_) {
287  Task t = q.PopFront();
288  for (int i = 0; i < spin_count && !t.f; i++) {
289  if (!cancelled_.load(std::memory_order_relaxed)) {
290  t = q.PopFront();
291  }
292  }
293  if (!t.f) {
294  if (!WaitForWork(waiter, &t)) {
295  return;
296  }
297  }
298  if (t.f) {
299  env_.ExecuteTask(t);
300  }
301  }
302  } else {
303  while (!cancelled_) {
304  Task t = q.PopFront();
305  if (!t.f) {
306  t = LocalSteal();
307  if (!t.f) {
308  t = GlobalSteal();
309  if (!t.f) {
310  // Leave one thread spinning. This reduces latency.
311  if (allow_spinning_ && !spinning_ && !spinning_.exchange(true)) {
312  for (int i = 0; i < spin_count && !t.f; i++) {
313  if (!cancelled_.load(std::memory_order_relaxed)) {
314  t = GlobalSteal();
315  } else {
316  return;
317  }
318  }
319  spinning_ = false;
320  }
321  if (!t.f) {
322  if (!WaitForWork(waiter, &t)) {
323  return;
324  }
325  }
326  }
327  }
328  }
329  if (t.f) {
330  env_.ExecuteTask(t);
331  }
332  }
333  }
334  }
335 
336  // Steal tries to steal work from other worker threads in the range [start,
337  // limit) in best-effort manner.
338  Task Steal(unsigned start, unsigned limit) {
339  PerThread* pt = GetPerThread();
340  const size_t size = limit - start;
341  unsigned r = Rand(&pt->rand);
342  // Reduce r into [0, size) range, this utilizes trick from
343  // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
344  eigen_plain_assert(all_coprimes_[size - 1].size() < (1<<30));
345  unsigned victim = ((uint64_t)r * (uint64_t)size) >> 32;
346  unsigned index = ((uint64_t) all_coprimes_[size - 1].size() * (uint64_t)r) >> 32;
347  unsigned inc = all_coprimes_[size - 1][index];
348 
349  for (unsigned i = 0; i < size; i++) {
350  eigen_plain_assert(start + victim < limit);
351  Task t = thread_data_[start + victim].queue.PopBack();
352  if (t.f) {
353  return t;
354  }
355  victim += inc;
356  if (victim >= size) {
357  victim -= size;
358  }
359  }
360  return Task();
361  }
362 
363  // Steals work within threads belonging to the partition.
365  PerThread* pt = GetPerThread();
366  unsigned partition = GetStealPartition(pt->thread_id);
367  // If thread steal partition is the same as global partition, there is no
368  // need to go through the steal loop twice.
369  if (global_steal_partition_ == partition) return Task();
370  unsigned start, limit;
371  DecodePartition(partition, &start, &limit);
372  AssertBounds(start, limit);
373 
374  return Steal(start, limit);
375  }
376 
377  // Steals work from any other thread in the pool.
379  return Steal(0, num_threads_);
380  }
381 
382 
383  // WaitForWork blocks until new work is available (returns true), or if it is
384  // time to exit (returns false). Can optionally return a task to execute in t
385  // (in such case t.f != nullptr on return).
386  bool WaitForWork(EventCount::Waiter* waiter, Task* t) {
387  eigen_plain_assert(!t->f);
388  // We already did best-effort emptiness check in Steal, so prepare for
389  // blocking.
390  ec_.Prewait();
391  // Now do a reliable emptiness check.
392  int victim = NonEmptyQueueIndex();
393  if (victim != -1) {
394  ec_.CancelWait();
395  if (cancelled_) {
396  return false;
397  } else {
398  *t = thread_data_[victim].queue.PopBack();
399  return true;
400  }
401  }
402  // Number of blocked threads is used as termination condition.
403  // If we are shutting down and all worker threads blocked without work,
404  // that's we are done.
405  blocked_++;
406  // TODO is blocked_ required to be unsigned?
407  if (done_ && blocked_ == static_cast<unsigned>(num_threads_)) {
408  ec_.CancelWait();
409  // Almost done, but need to re-check queues.
410  // Consider that all queues are empty and all worker threads are preempted
411  // right after incrementing blocked_ above. Now a free-standing thread
412  // submits work and calls destructor (which sets done_). If we don't
413  // re-check queues, we will exit leaving the work unexecuted.
414  if (NonEmptyQueueIndex() != -1) {
415  // Note: we must not pop from queues before we decrement blocked_,
416  // otherwise the following scenario is possible. Consider that instead
417  // of checking for emptiness we popped the only element from queues.
418  // Now other worker threads can start exiting, which is bad if the
419  // work item submits other work. So we just check emptiness here,
420  // which ensures that all worker threads exit at the same time.
421  blocked_--;
422  return true;
423  }
424  // Reached stable termination state.
425  ec_.Notify(true);
426  return false;
427  }
428  ec_.CommitWait(waiter);
429  blocked_--;
430  return true;
431  }
432 
434  PerThread* pt = GetPerThread();
435  // We intentionally design NonEmptyQueueIndex to steal work from
436  // anywhere in the queue so threads don't block in WaitForWork() forever
437  // when all threads in their partition go to sleep. Steal is still local.
438  const size_t size = thread_data_.size();
439  unsigned r = Rand(&pt->rand);
440  unsigned inc = all_coprimes_[size - 1][r % all_coprimes_[size - 1].size()];
441  unsigned victim = r % size;
442  for (unsigned i = 0; i < size; i++) {
443  if (!thread_data_[victim].queue.Empty()) {
444  return victim;
445  }
446  victim += inc;
447  if (victim >= size) {
448  victim -= size;
449  }
450  }
451  return -1;
452  }
453 
454  static EIGEN_STRONG_INLINE uint64_t GlobalThreadIdHash() {
455  return std::hash<std::thread::id>()(std::this_thread::get_id());
456  }
457 
458  EIGEN_STRONG_INLINE PerThread* GetPerThread() {
459 #ifndef EIGEN_THREAD_LOCAL
460  static PerThread dummy;
461  auto it = per_thread_map_.find(GlobalThreadIdHash());
462  if (it == per_thread_map_.end()) {
463  return &dummy;
464  } else {
465  return it->second.get();
466  }
467 #else
468  EIGEN_THREAD_LOCAL PerThread per_thread_;
469  PerThread* pt = &per_thread_;
470  return pt;
471 #endif
472  }
473 
474  static EIGEN_STRONG_INLINE unsigned Rand(uint64_t* state) {
475  uint64_t current = *state;
476  // Update the internal state
477  *state = current * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL;
478  // Generate the random output (using the PCG-XSH-RS scheme)
479  return static_cast<unsigned>((current ^ (current >> 22)) >>
480  (22 + (current >> 61)));
481  }
482 };
483 
485 
486 } // namespace Eigen
487 
488 #endif // EIGEN_CXX11_THREADPOOL_NONBLOCKING_THREAD_POOL_H
Array< int, 3, 1 > b
#define eigen_plain_assert(condition)
Definition: Assert.h:156
#define EIGEN_OVERRIDE
Definition: Macros.h:1279
#define EIGEN_FINAL
Definition: Macros.h:1280
#define EIGEN_UNUSED_VARIABLE(var)
Definition: Macros.h:957
#define EIGEN_MUTEX
Definition: ThreadPool:55
void CommitWait(Waiter *w)
Definition: EventCount.h:81
void Notify(bool notifyAll)
Definition: EventCount.h:132
The MaxSizeVector class.
Definition: MaxSizeVector.h:31
void push_back(const T &t)
Definition: MaxSizeVector.h:82
Work PushBack(Work w)
Definition: RunQueue.h:86
Work PopFront()
Definition: RunQueue.h:70
Work PushFront(Work w)
Definition: RunQueue.h:55
void AssertBounds(int start, int end)
void Cancel() EIGEN_OVERRIDE
static uint64_t GlobalThreadIdHash()
bool WaitForWork(EventCount::Waiter *waiter, Task *t)
std::atomic< unsigned > blocked_
int CurrentThreadId() const EIGEN_FINAL
void Schedule(std::function< void()> fn) EIGEN_OVERRIDE
void ComputeCoprimes(int N, MaxSizeVector< unsigned > *coprimes)
ThreadPoolTempl(int num_threads, bool allow_spinning, Environment env=Environment())
void ScheduleWithHint(std::function< void()> fn, int start, int limit) override
void SetStealPartition(size_t i, unsigned val)
static unsigned Rand(uint64_t *state)
MaxSizeVector< ThreadData > thread_data_
std::unordered_map< uint64_t, std::unique_ptr< PerThread > > per_thread_map_
static const int kMaxPartitionBits
Environment::EnvThread Thread
std::unique_ptr< Barrier > init_barrier_
int NumThreads() const EIGEN_FINAL
void DecodePartition(unsigned val, unsigned *start, unsigned *limit)
ThreadPoolTempl(int num_threads, Environment env=Environment())
unsigned EncodePartition(unsigned start, unsigned limit)
std::atomic< bool > spinning_
MaxSizeVector< MaxSizeVector< unsigned > > all_coprimes_
std::atomic< bool > cancelled_
void SetStealPartitions(const std::vector< std::pair< unsigned, unsigned >> &partitions)
RunQueue< Task, 1024 > Queue
MaxSizeVector< EventCount::Waiter > waiters_
void WorkerLoop(int thread_id)
Task Steal(unsigned start, unsigned limit)
static const lastp1_t end
std::uint64_t uint64_t
Definition: Meta.h:41
: InteropHeaders
Definition: Core:139
ThreadPoolTempl< StlThreadEnvironment > ThreadPool