
#ifndef PLS_SCHEDULER_H
#define PLS_SCHEDULER_H

#include <atomic>

#include "pls/internal/helpers/profiler.h"

#include "pls/internal/base/thread.h"
#include "pls/internal/base/barrier.h"

#include "pls/internal/scheduling/scheduler_memory.h"
#include "pls/internal/scheduling/thread_state.h"

namespace pls {
namespace internal {
namespace scheduling {

struct task;

/**
 * The scheduler is the central part of the dispatching-framework.
 * It manages a pool of worker threads (creates, sleeps/wakes up, destroys)
 * and allows to execute parallel sections.
 *
 * It works in close relation with the 'task' class for scheduling.
 */
class scheduler {
 public:
  /**
   * Initializes a scheduler instance with the given number of threads.
   * This will spawn the threads and put them to sleep, ready to process an
   * upcoming parallel section.
   *
   * @param memory All memory is allocated statically, thus the user is required to provide the memory instance.
   * @param num_threads The number of worker threads to be created.
   */
  explicit scheduler(scheduler_memory &memory, unsigned int num_threads, bool reuse_thread = true);

  /**
   * The scheduler is implicitly terminated as soon as it leaves the scope.
   */
  ~scheduler();

  /**
   * Wakes up the thread pool.
   * Code inside the Function lambda can invoke all parallel APIs.
   * This is meant to cleanly sleep and wake up the scheduler during an application run,
   * e.g. to run parallel code on a timer loop/after interrupts.
   *
   * @param work_section generic function or lambda to be executed in the scheduler's context.
   */
  template<typename Function>
  void perform_work(Function work_section);

  template<typename Function>
  static void spawn(Function &&lambda);
  static void sync();

  thread_state &thread_state_for(size_t id);

  /**
   * Explicitly terminate the worker threads. Scheduler must not be used after this.
   */
  void terminate();

  unsigned int num_threads() const { return num_threads_; }

 private:
  static void work_thread_main_loop();
  void work_thread_work_section();

  const unsigned int num_threads_;
  const bool reuse_thread_;
  scheduler_memory &memory_;

  base::barrier sync_barrier_;

  class init_function;
  template<typename F>
  class init_function_impl;

  init_function *main_thread_starter_function_;
  std::atomic<bool> work_section_done_;

  bool terminated_;
};

}
}
}
#include "scheduler_impl.h"

#endif //PLS_SCHEDULER_H
