30#include <condition_variable>
49 void work(
unsigned iThread)
52 std::unique_lock lock(_mutex);
53 _available.wait(lock, [&]() {
54 return !_queue.empty()
58 std::function<void()> task = std::move(_queue.front());
70 mutable std::mutex _mutex;
72 std::atomic<bool> _waiting;
73 std::atomic<bool> _active;
75 std::atomic<std::size_t> _taskCount;
77 std::condition_variable _available;
78 std::condition_variable _done;
80 std::vector<std::thread> _threads;
81 std::queue<std::function<void()>> _queue;
99 void init(
int nThreads,
bool verbose)
104 _threads.resize(nThreads);
106 for (
unsigned iThread=0; iThread < _threads.size(); ++iThread) {
107 _threads[iThread] = std::thread(&ThreadPool::work,
this, iThread);
110 clout <<
"Sucessfully initialized, numThreads=" << std::to_string(_threads.size()) << std::endl;
118 _available.notify_all();
119 for (std::thread& thread : _threads) {
127 return _threads.size();
131 template <
typename F>
136 const std::scoped_lock lock(_mutex);
140 _available.notify_one();
144 template <
typename F,
typename R = std::invoke_result_t<std::decay_t<F>>>
148 auto packagedF = std::make_shared<std::packaged_task<R()>>(f);
150 const std::scoped_lock lock(_mutex);
151 _queue.push([packagedF]() {
156 _available.notify_one();
157 return packagedF->get_future();
165 std::unique_lock lock(_mutex);
166 _done.wait(lock, [&]() {
167 return _taskCount == 0;
173 template <
typename T>
174 void waitFor(std::vector<std::future<T>>& futures)
176 for (
auto& future : futures) {
class for marking output with some text
Pool of threads for CPU-based background processing.
void init(int nThreads, bool verbose)
Initialization to be called by olbInit.
void scheduleAndForget(F &&f)
Schedule F, tracking neither its return value nor completion.
unsigned size() const
Returns number of threads.
std::future< R > schedule(F &&f)
Schedule F and return future of its return value.
void waitFor(std::vector< std::future< T > > &futures)
Blocks until all tasks producing the given futures are completed.
void wait()
Blocks until all tasks are completed.
Top level namespace for all of OpenLB.
#define OLB_PRECONDITION(COND)