summaryrefslogtreecommitdiff
path: root/competition/job.cpp
diff options
context:
space:
mode:
authorTom Smeding <tom.smeding@gmail.com>2018-07-21 22:03:31 +0200
committerTom Smeding <tom.smeding@gmail.com>2018-07-21 22:03:31 +0200
commitf0b6d1b9c46578183b427bcec4bbe99ab10c7b97 (patch)
tree111df40d4485f7dc7a66d0d463688021474512c1 /competition/job.cpp
parent53291958e0cda68ed762c0dfb36c0602f876c06d (diff)
competition: reorganisation and multithread
Diffstat (limited to 'competition/job.cpp')
-rw-r--r--competition/job.cpp51
1 files changed, 51 insertions, 0 deletions
diff --git a/competition/job.cpp b/competition/job.cpp
new file mode 100644
index 0000000..043074e
--- /dev/null
+++ b/competition/job.cpp
@@ -0,0 +1,51 @@
+#include <chrono>
+#include <cassert>
+#include "job.h"
+
+void Scheduler::workerEntry() {
+ while (true) {
+ Job *job = nullptr;
+
+ {
+ lock_guard commMutGuard(commMut);
+ if (terminateFlag) break;
+ if (jobs.size() > 0) {
+ job = jobs.front();
+ jobs.pop();
+ }
+ }
+
+ if (job) {
+ job->callback();
+ } else {
+ this_thread::sleep_for(chrono::milliseconds(100));
+ }
+ }
+}
+
+Scheduler::Scheduler(int nthreads)
+ : nthreads(nthreads) {
+
+ assert(nthreads > 0);
+
+ workers.reserve(nthreads);
+ for (int i = 0; i < nthreads; i++) {
+ workers.emplace_back([this]() { workerEntry(); });
+ }
+}
+
+Scheduler::~Scheduler() {
+ finish();
+}
+
+void Scheduler::submit(const function<void()> &func) {
+ Job *job = new Job(func);
+ lock_guard commMutGuard(commMut);
+ jobs.push(job);
+}
+
+void Scheduler::finish() {
+ for (int i = 0; i < nthreads; i++) {
+ workers[i].join();
+ }
+}