llir-opt  0.0.1
Low-Level Post-Link Optimiser for OCaml and C
job_runner.h
1 // This file if part of the llir-opt project.
2 // Licensing information can be found in the LICENSE file.
3 // (C) 2018 Nandor Licker. All rights reserved.
4 
5 #pragma once
6 
7 #include <atomic>
8 #include <thread>
9 
10 #include "timeout.h"
11 
12 
13 
17 template <typename Task, typename Result>
18 class JobRunner {
19 public:
21  JobRunner(unsigned threadCount = 1) : threadCount_(threadCount) {}
22 
24  virtual ~JobRunner()
25  {
26  }
27 
29  void Execute(const Timeout &timeout)
30  {
31  std::vector<std::thread> threads;
32  for (unsigned i = 0; i < threadCount_; ++i) {
33  threads.emplace_back([this, &timeout] {
34  while (true) {
35  // If timeout reached, break.
36  if (timeout) {
37  return;
38  }
39 
40  // Get a new task to execute.
41  Task task;
42  {
43  std::lock_guard<std::mutex> guard(lock_);
44  if (auto newTask = Request()) {
45  task = std::move(*newTask);
46  } else {
47  return;
48  }
49  }
50 
51  // Run the task.
52  Result result = Run(std::move(task));
53 
54  // Post the result.
55  {
56  std::lock_guard<std::mutex> guard(lock_);
57  Post(std::move(result));
58  }
59  }
60  });
61  }
62 
63  for (std::thread &thread : threads) {
64  thread.join();
65  }
66  }
67 
68 protected:
71  virtual std::optional<Task> Request() = 0;
72 
74  virtual Result Run(Task &&task) = 0;
75 
77  virtual void Post(Result &&result) = 0;
78 
79 private:
81  unsigned threadCount_;
83  std::mutex lock_;
84 };
JobRunner::~JobRunner
virtual ~JobRunner()
Cleanup on exit.
Definition: job_runner.h:24
JobRunner::Request
virtual std::optional< Task > Request()=0
JobRunner::Execute
void Execute(const Timeout &timeout)
Run the pool.
Definition: job_runner.h:29
JobRunner::Run
virtual Result Run(Task &&task)=0
Run the task on a separate thread.
JobRunner::JobRunner
JobRunner(unsigned threadCount=1)
Initialises the job runner.
Definition: job_runner.h:21
JobRunner::Post
virtual void Post(Result &&result)=0
Post the result of a task.
Timeout
Definition: timeout.h:14
JobRunner
Definition: job_runner.h:18