Skip to main content

JobSystem.ixx File

Thread-pool-based job scheduler with blocking wait semantics. More...

Included Headers

#include <condition_variable> #include <thread> #include <cstddef> #include <queue> #include <vector> #include <functional>

Namespaces Index

namespacehelios
namespaceengine
namespacecore
namespacethread

Classes Index

classJobSystem

A fixed-size thread pool for parallel job execution. More...

Description

Thread-pool-based job scheduler with blocking wait semantics.

File Listing

The file content with the documentation metadata removed is:

1
5module;
6
7#include <condition_variable>
8#include <thread>
9#include <cstddef>
10#include <queue>
11#include <vector>
12#include <functional>
13
14export module helios.engine.core.thread.JobSystem;
15
16
18
38 class JobSystem {
39
40 std::queue<std::function<void()>> jobQueue_;
41 std::mutex mutex_;
42 std::condition_variable_any jobCondition_;
43 std::condition_variable doneCondition_;
44
46 std::size_t maxWorkerCount_;
47
49 std::size_t pendingJobCount_ = 0;
50
51 std::vector<std::jthread> workerThreads_;
52
53 public:
54
61 explicit JobSystem(const std::size_t maxWorkerCount) : maxWorkerCount_(maxWorkerCount) {
62
63 workerThreads_.reserve(maxWorkerCount);
64
65 for (std::size_t i = 0; i < maxWorkerCount; ++i) {
66 workerThreads_.emplace_back([this](std::stop_token stopToken) {
67 while (!stopToken.stop_requested()) {
68 std::function<void()> job;
69
70 {
71 std::unique_lock<std::mutex> lock(mutex_);
72
73 if (!jobCondition_.wait(lock, stopToken, [&] {
74 return !jobQueue_.empty();
75 })) {
76 return;
77 }
78
79 job = std::move(jobQueue_.front());
80 jobQueue_.pop();
81 }
82
83 job();
84 }
85
86 });
87 }
88 }
89
102 template<typename Fn>
103 void runAndWait(std::size_t jobCount, Fn&& fn) {
104 {
105 std::lock_guard lock(mutex_);
106
107 pendingJobCount_ = jobCount;
108
109 for (std::size_t i = 0; i < jobCount; ++i) {
110
111 jobQueue_.emplace([this, i, &fn] {
112 fn(i);
113
114 {
115 std::lock_guard lok(mutex_);
116 --pendingJobCount_;
117 }
118
119 doneCondition_.notify_one();
120 });
121
122 }
123 }
124
125 jobCondition_.notify_all();
126
127 std::unique_lock<std::mutex> lock(mutex_);
128
129 doneCondition_.wait(lock, [&] {
130 return pendingJobCount_ == 0;
131 });
132 }
133
134 };
135
136}

Generated via doxygen2docusaurus 2.0.0 by Doxygen 1.9.8.