5#include <condition_variable>
12#ifdef POLYFEM_WITH_TBB
13#include <tbb/task_arena.h>
23#if defined(POLYFEM_WITH_CPP_THREADS) || defined(POLYFEM_WITH_TBB)
42 std::unique_lock<std::mutex> lock(
state_->mutex);
43 state_->changed.wait(lock, [&] {
48 throw std::logic_error(
"Cannot enqueue output after finishing the writer");
53 throw std::invalid_argument(
"An output frame must have a write operation");
66 std::lock_guard<std::mutex> failed(
state_->mutex);
67 state_->error = std::current_exception();
71 state_->changed.notify_all();
77 state_->changed.notify_all();
82 state_->pending = std::move(job);
84 state_->changed.notify_all();
89 std::unique_lock<std::mutex> lock(
state_->mutex);
97 std::lock_guard<std::mutex> lock(
state_->mutex);
100 state_->changed.notify_all();
103 std::unique_lock<std::mutex> lock(
state_->mutex);
104 state_->changed.wait(lock, [&] {
return !
state_->active; });
108 std::lock_guard<std::mutex> lock(
state_->mutex);
124#ifdef POLYFEM_WITH_CPP_THREADS
127#elif defined(POLYFEM_WITH_TBB)
128 tbb::task_arena simulation_arena(
static_cast<int>(threads - 1));
129 simulation_arena.execute(compute);
149 std::rethrow_exception(
state_->error);
152 static void run(
const std::shared_ptr<State> &state)
159 std::unique_lock<std::mutex> lock(state->mutex);
160 state->changed.wait(lock, [&] {
return state->pending || state->closed; });
163 job = std::exchange(state->pending, {});
164 state->active =
true;
166 state->changed.notify_all();
176 std::lock_guard<std::mutex> lock(state->mutex);
177 state->error = std::current_exception();
178 state->active =
false;
179 state->closed =
true;
180 discarded = std::exchange(state->pending, {});
182 state->changed.notify_all();
186 std::lock_guard<std::mutex> lock(state->mutex);
187 state->active =
false;
189 state->changed.notify_all();
197#if defined(POLYFEM_WITH_CPP_THREADS) || defined(POLYFEM_WITH_TBB)
199#ifdef POLYFEM_WITH_TBB
200 tbb::task_arena output_arena(1);
201 output_arena.execute([&] {
run(state); });
210 std::shared_ptr<State>
state_ = std::make_shared<State>();
Impl(const bool asynchronous)
static void run(const std::shared_ptr< State > &state)
bool asynchronous() const
std::shared_ptr< State > state_
void execute(const Job &compute)
void enqueue(const Prepare &prepare)
std::unique_ptr< Impl > impl_
void enqueue(const Prepare &prepare)
Wait for the pending slot, then prepare its owned frame on the caller.
void flush()
Wait for all accepted frames and propagate output failures.
void finish()
Drain accepted frames, stop the worker, and propagate output failures.
bool asynchronous() const
std::function< Job()> Prepare
void execute(const Job &compute)
Run simulation work with one thread reserved for asynchronous output.
std::function< void()> Job
OutputWriter(bool asynchronous=true)
Restrict parallel work on the current thread and its CPP worker calls.
std::condition_variable changed