11#ifndef EIGEN_THREADPOOL_NONBLOCKING_THREAD_POOL_H
12#define EIGEN_THREADPOOL_NONBLOCKING_THREAD_POOL_H
15#include "./InternalHeaderCheck.h"
19template <
typename Environment>
20class ThreadPoolTempl :
public Eigen::ThreadPoolInterface {
22 using Thread =
typename Environment::EnvThread;
23 using Task =
typename Environment::Task;
24 using Queue = RunQueue<Task, 1024>;
27 ThreadPoolTempl* pool =
nullptr;
33 constexpr ThreadData() =
default;
34 std::unique_ptr<Thread> thread;
35 std::atomic<unsigned> steal_partition{0};
39 ThreadPoolTempl(
int num_threads, Environment env = Environment()) : ThreadPoolTempl(num_threads, true, env) {}
41 ThreadPoolTempl(
int num_threads,
bool allow_spinning, Environment env = Environment())
43 num_threads_(num_threads),
44 allow_spinning_(allow_spinning),
49 allow_spinning && num_threads > 0 ? kSpinCount / kMaxSpinningThreads / num_threads : 0),
50 thread_data_(num_threads),
51 all_coprimes_(num_threads),
52 waiters_(num_threads),
53 global_steal_partition_(EncodePartition(0, num_threads_)),
59 waiters_.resize(num_threads_);
67 eigen_plain_assert(num_threads_ < kMaxThreads);
68 for (
int i = 1; i <= num_threads_; ++i) {
69 all_coprimes_.emplace_back(i);
70 ComputeCoprimes(i, &all_coprimes_.back());
72#ifndef EIGEN_THREAD_LOCAL
73 init_barrier_ = std::make_unique<Barrier>(num_threads_);
75 thread_data_.resize(num_threads_);
76 for (
int i = 0; i < num_threads_; i++) {
77 SetStealPartition(i, EncodePartition(0, num_threads_));
78 thread_data_[i].thread.reset(env_.CreateThread([
this, i]() { WorkerLoop(i); }));
80#ifndef EIGEN_THREAD_LOCAL
83 init_barrier_->Wait();
99 for (
size_t i = 0; i < thread_data_.size(); i++) {
100 while (!thread_data_[i].queue.Empty()) thread_data_[i].queue.PopBack();
105 for (
size_t i = 0; i < thread_data_.size(); ++i) thread_data_[i].thread.reset();
110 for (
size_t i = 0; i < thread_data_.size(); i++) {
111 thread_data_[i].queue.Flush();
116 void SetStealPartitions(
const std::vector<std::pair<unsigned, unsigned>>& partitions) {
117 eigen_plain_assert(partitions.size() ==
static_cast<std::size_t
>(num_threads_));
120 for (
int i = 0; i < num_threads_; i++) {
121 const auto& pair = partitions[i];
122 unsigned start = pair.first, end = pair.second;
123 AssertBounds(start, end);
124 unsigned val = EncodePartition(start, end);
125 SetStealPartition(i, val);
129 void Schedule(std::function<
void()> fn) EIGEN_OVERRIDE { ScheduleWithHint(std::move(fn), 0, num_threads_); }
131 void ScheduleWithHint(std::function<
void()> fn,
int start,
int limit)
override {
132 Task t = env_.CreateTask(std::move(fn));
133 PerThread* pt = GetPerThread();
134 if (pt->pool ==
this) {
136 Queue& q = thread_data_[pt->thread_id].queue;
137 t = q.PushFront(std::move(t));
141 eigen_plain_assert(start < limit);
142 eigen_plain_assert(limit <= num_threads_);
143 int num_queues = limit - start;
144#ifdef EIGEN_THREAD_LOCAL
145 int rnd = Rand(&pt->rand) % num_queues;
148 int rnd = SharedRand() % num_queues;
150 eigen_plain_assert(start + rnd < limit);
151 Queue& q = thread_data_[start + rnd].queue;
152 t = q.PushBack(std::move(t));
162 if (IsNotifyParkedThreadRequired()) {
171 void MaybeGetTask(Task* t) {
172 PerThread* pt = GetPerThread();
173 const int thread_id = pt->thread_id;
175 if (pt->pool !=
this)
return;
176 Queue& q = thread_data_[thread_id].queue;
179 if (num_threads_ == 1) {
186 for (
int i = 0; i < spin_count_ && !t->f; ++i) *t = q.PopFront();
188 if (EIGEN_PREDICT_FALSE(!t->f)) *t = LocalSteal();
189 if (EIGEN_PREDICT_FALSE(!t->f)) *t = GlobalSteal();
190 if (EIGEN_PREDICT_FALSE(!t->f)) {
191 if (allow_spinning_ && StartSpinning()) {
192 for (
int i = 0; i < spin_count_ && !t->f; ++i) *t = GlobalSteal();
194 bool has_no_notify_task = StopSpinning();
197 if (has_no_notify_task) {
199 if (NonEmptyQueueIndex() != -1) ec_.Notify(
false);
209 void Cancel() EIGEN_OVERRIDE {
214#ifdef EIGEN_THREAD_ENV_SUPPORTS_CANCELLATION
215 for (
size_t i = 0; i < thread_data_.size(); i++) {
216 thread_data_[i].thread->OnCancel();
224 int NumThreads() const EIGEN_FINAL {
return num_threads_; }
226 int CurrentThreadId() const EIGEN_FINAL {
227 const PerThread* pt =
const_cast<ThreadPoolTempl*
>(
this)->GetPerThread();
228 if (pt->pool ==
this) {
229 return pt->thread_id;
243 static constexpr int kMaxPartitionBits = 16;
244 static constexpr int kMaxThreads = 1 << kMaxPartitionBits;
246 inline unsigned EncodePartition(
unsigned start,
unsigned limit) {
return (start << kMaxPartitionBits) | limit; }
248 inline void DecodePartition(
unsigned val,
unsigned* start,
unsigned* limit) {
249 *limit = val & (kMaxThreads - 1);
250 val >>= kMaxPartitionBits;
254 void AssertBounds(
int start,
int end) {
255 eigen_plain_assert(start >= 0);
256 eigen_plain_assert(start < end);
257 eigen_plain_assert(end <= num_threads_);
262 inline void SetStealPartition(
size_t i,
unsigned val) {
263 thread_data_[i].steal_partition.store(val, std::memory_order_relaxed);
266 inline unsigned GetStealPartition(
int i) {
return thread_data_[i].steal_partition.load(std::memory_order_relaxed); }
268 void ComputeCoprimes(
int N, MaxSizeVector<unsigned>* coprimes) {
269 for (
int i = 1; i <= N; i++) {
279 coprimes->push_back(i);
285 static constexpr int kMaxSpinningThreads = 1;
289 static constexpr int kSpinCount = 5000;
299 static constexpr int kMinActiveThreadsToStartSpinning = 4;
301 struct SpinningState {
312 static constexpr uint64_t kNumSpinningMask = 0x00000000FFFFFFFF;
313 static constexpr uint64_t kNumNoNotifyMask = 0xFFFFFFFF00000000;
314 static constexpr uint64_t kNumNoNotifyShift = 32;
316 uint64_t num_spinning;
317 uint64_t num_no_notification;
321 static SpinningState Decode(uint64_t state) {
322 uint64_t num_spinning = (state & kNumSpinningMask);
323 uint64_t num_no_notification = (state & kNumNoNotifyMask) >> kNumNoNotifyShift;
325 eigen_plain_assert(num_no_notification <= num_spinning);
326 return {num_spinning, num_no_notification};
330 uint64_t Encode()
const {
331 eigen_plain_assert(num_no_notification <= num_spinning);
332 return (num_no_notification << kNumNoNotifyShift) | num_spinning;
337 const int num_threads_;
338 const bool allow_spinning_;
339 const int spin_count_;
340 MaxSizeVector<ThreadData> thread_data_;
341 MaxSizeVector<MaxSizeVector<unsigned>> all_coprimes_;
342 MaxSizeVector<EventCount::Waiter> waiters_;
343 unsigned global_steal_partition_;
344 std::atomic<uint64_t> spinning_state_;
345 std::atomic<unsigned> blocked_;
346 std::atomic<bool> done_;
347 std::atomic<bool> cancelled_;
349#ifndef EIGEN_THREAD_LOCAL
350 std::unique_ptr<Barrier> init_barrier_;
351 EIGEN_MUTEX per_thread_map_mutex_;
352 std::unordered_map<uint64_t, std::unique_ptr<PerThread>> per_thread_map_;
355 unsigned NumActiveThreads()
const {
return num_threads_ - blocked_.load(); }
358 void WorkerLoop(
int thread_id) {
359#ifndef EIGEN_THREAD_LOCAL
360 auto new_pt = std::make_unique<PerThread>();
361 per_thread_map_mutex_.lock();
362 bool insertOK = per_thread_map_.emplace(GlobalThreadIdHash(), std::move(new_pt)).second;
363 eigen_plain_assert(insertOK);
364 EIGEN_UNUSED_VARIABLE(insertOK);
365 per_thread_map_mutex_.unlock();
366 init_barrier_->Notify();
367 init_barrier_->Wait();
369 PerThread* pt = GetPerThread();
371 pt->rand = GlobalThreadIdHash();
372 pt->thread_id = thread_id;
374 while (!cancelled_.load(std::memory_order_relaxed)) {
378 if (EIGEN_PREDICT_FALSE(!t.f)) {
379 EventCount::Waiter* waiter = &waiters_[pt->thread_id];
380 if (!WaitForWork(waiter, &t))
return;
382 if (EIGEN_PREDICT_TRUE(t.f)) env_.ExecuteTask(t);
388 Task Steal(
unsigned start,
unsigned limit) {
389 PerThread* pt = GetPerThread();
390 const size_t size = limit - start;
391 unsigned r = Rand(&pt->rand);
394 eigen_plain_assert(all_coprimes_[size - 1].size() < (1 << 30));
395 unsigned victim = ((uint64_t)r * (uint64_t)size) >> 32;
396 unsigned index = ((uint64_t)all_coprimes_[size - 1].size() * (uint64_t)r) >> 32;
397 unsigned inc = all_coprimes_[size - 1][index];
399 for (
unsigned i = 0; i < size; i++) {
400 eigen_plain_assert(start + victim < limit);
401 Task t = thread_data_[start + victim].queue.PopBack();
406 if (victim >= size) {
407 victim -=
static_cast<unsigned int>(size);
415 PerThread* pt = GetPerThread();
416 unsigned partition = GetStealPartition(pt->thread_id);
419 if (global_steal_partition_ == partition)
return Task();
420 unsigned start, limit;
421 DecodePartition(partition, &start, &limit);
422 AssertBounds(start, limit);
424 return Steal(start, limit);
428 Task GlobalSteal() {
return Steal(0, num_threads_); }
433 bool WaitForWork(EventCount::Waiter* waiter, Task* t) {
434 eigen_plain_assert(!t->f);
447 int victim = NonEmptyQueueIndex();
453 *t = thread_data_[victim].queue.PopBack();
462 if (done_ && blocked_ ==
static_cast<unsigned>(num_threads_)) {
469 if (NonEmptyQueueIndex() != -1) {
483 ec_.CommitWait(waiter);
488 int NonEmptyQueueIndex() {
489 PerThread* pt = GetPerThread();
493 const size_t size = thread_data_.size();
494 unsigned r = Rand(&pt->rand);
495 unsigned inc = all_coprimes_[size - 1][r % all_coprimes_[size - 1].size()];
496 unsigned victim = r % size;
497 for (
unsigned i = 0; i < size; i++) {
498 if (!thread_data_[victim].queue.Empty()) {
502 if (victim >= size) {
503 victim -=
static_cast<unsigned int>(size);
513 bool StartSpinning() {
514 if (NumActiveThreads() > kMinActiveThreadsToStartSpinning)
return false;
516 uint64_t spinning = spinning_state_.load(std::memory_order_relaxed);
518 SpinningState state = SpinningState::Decode(spinning);
520 if ((state.num_spinning - state.num_no_notification) >= kMaxSpinningThreads) {
525 ++state.num_spinning;
527 if (spinning_state_.compare_exchange_weak(spinning, state.Encode(), std::memory_order_relaxed)) {
538 bool StopSpinning() {
539 uint64_t spinning = spinning_state_.load(std::memory_order_relaxed);
541 SpinningState state = SpinningState::Decode(spinning);
544 --state.num_spinning;
547 bool has_no_notify_task = state.num_no_notification > 0;
548 if (has_no_notify_task) --state.num_no_notification;
551 if (spinning_state_.compare_exchange_weak(spinning, state.Encode(), std::memory_order_acquire)) {
552 return has_no_notify_task;
561 bool IsNotifyParkedThreadRequired() {
562 uint64_t spinning = spinning_state_.load(std::memory_order_relaxed);
564 SpinningState state = SpinningState::Decode(spinning);
569 if (state.num_no_notification == state.num_spinning)
return true;
572 ++state.num_no_notification;
575 if (spinning_state_.compare_exchange_weak(spinning, state.Encode(), std::memory_order_release,
576 std::memory_order_relaxed)) {
582 static EIGEN_STRONG_INLINE uint64_t GlobalThreadIdHash() {
583 return std::hash<std::thread::id>()(std::this_thread::get_id());
586 EIGEN_STRONG_INLINE PerThread* GetPerThread() {
587#ifndef EIGEN_THREAD_LOCAL
588 static PerThread dummy;
589 auto it = per_thread_map_.find(GlobalThreadIdHash());
590 if (it == per_thread_map_.end()) {
593 return it->second.get();
596 EIGEN_THREAD_LOCAL PerThread per_thread_;
597 PerThread* pt = &per_thread_;
602#ifndef EIGEN_THREAD_LOCAL
604 static unsigned SharedRand() {
605 static std::atomic<uint64_t> shared_state(0);
606 uint64_t state = shared_state.fetch_add(0x9E3779B97F4A7C15ULL, std::memory_order_relaxed);
611 static EIGEN_STRONG_INLINE
unsigned Rand(uint64_t* state) {
612 uint64_t current = *state;
614 *state = current * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL;
616 return static_cast<unsigned>((current ^ (current >> 22)) >> (22 + (current >> 61)));
620using ThreadPool = ThreadPoolTempl<StlThreadEnvironment>;