abstract_task.cpp 2.43 KB
Newer Older
1
#include "pls/internal/helpers/profiler.h"
2

3
#include "pls/internal/scheduling/thread_state.h"
4
#include "pls/internal/scheduling/abstract_task.h"
5
#include "pls/internal/scheduling/scheduler.h"
6 7

namespace pls {
8 9
namespace internal {
namespace scheduling {
10

11 12 13 14
bool abstract_task::steal_work() {
  PROFILE_STEALING("abstract_task::steal_work")
  const auto my_state = base::this_thread::state<thread_state>();
  const auto my_scheduler = my_state->scheduler_;
15

16 17
  const size_t my_id = my_state->id_;
  const size_t offset = my_state->random_() % my_scheduler->num_threads();
18
  const size_t max_tries = my_scheduler->num_threads(); // TODO: Tune this value
19 20 21 22 23 24
  for (size_t i = 0; i < max_tries; i++) {
    size_t target = (offset + i) % my_scheduler->num_threads();
    if (target == my_id) {
      continue;
    }
    auto target_state = my_scheduler->thread_state_for(target);
25

26 27 28
    if (!target_state->lock_.reader_try_lock()) {
      continue;
    }
29

30 31 32 33
    // Dig down to our level
    PROFILE_STEALING("Go to our level")
    abstract_task *current_task = target_state->root_task_;
    while (current_task != nullptr && current_task->depth() < depth()) {
34
      current_task = current_task->child();
35 36
    }
    PROFILE_END_BLOCK
37

38 39 40 41 42 43 44 45
    // Try to steal 'internal', e.g. for_join_sub_tasks in a fork_join_task constellation
    PROFILE_STEALING("Internal Steal")
    if (current_task != nullptr) {
      // See if it equals our type and depth of task
      if (current_task->unique_id_ == unique_id_ &&
          current_task->depth_ == depth_) {
        if (internal_stealing(current_task)) {
          // internal steal was a success, hand it back to the internal scheduler
46
          target_state->lock_.reader_unlock();
47 48
          return true;
        }
49

50
        // No success, we need to steal work from a deeper level using 'top level task stealing'
51
        current_task = current_task->child();
52 53 54
      }
    }
    PROFILE_END_BLOCK;
55 56


57 58 59 60 61 62
    // Execute 'top level task steal' if possible
    // (only try deeper tasks to keep depth restricted stealing).
    PROFILE_STEALING("Top Level Steal")
    while (current_task != nullptr) {
      auto lock = &target_state->lock_;
      if (current_task->split_task(lock)) {
63
        // top level steal was a success (we did a top level task steal)
64 65
        return false;
      }
66

67
      current_task = current_task->child_task_;
68
    }
69
    PROFILE_END_BLOCK;
70
    target_state->lock_.reader_unlock();
71 72 73 74 75 76 77 78
  }

  // internal steal was no success
  return false;
}

}
}
79
}