PolyFEM
Loading...
Searching...
No Matches
OutputWriter.cpp
Go to the documentation of this file.
1#include "OutputWriter.hpp"
2
4
5#include <condition_variable>
6#include <exception>
7#include <mutex>
8#include <stdexcept>
9#include <thread>
10#include <utility>
11
12#ifdef POLYFEM_WITH_TBB
13#include <tbb/task_arena.h>
14#endif
15
16namespace polyfem::io
17{
19 {
20 public:
21 explicit Impl(const bool asynchronous)
22 {
23#if defined(POLYFEM_WITH_CPP_THREADS) || defined(POLYFEM_WITH_TBB)
25#endif
26 }
27
29 {
30 try
31 {
32 finish();
33 }
34 catch (...)
35 {
36 // Explicit finish/flush/enqueue calls report worker errors.
37 }
38 }
39
40 void enqueue(const Prepare &prepare)
41 {
42 std::unique_lock<std::mutex> lock(state_->mutex);
43 state_->changed.wait(lock, [&] {
44 return (!state_->pending && (asynchronous_ || !state_->active)) || state_->closed || state_->error;
45 });
47 if (state_->closed)
48 throw std::logic_error("Cannot enqueue output after finishing the writer");
49
50 // Preparing after the slot becomes free bounds retained frame memory.
51 Job job = prepare();
52 if (!job)
53 throw std::invalid_argument("An output frame must have a write operation");
54 if (!asynchronous_)
55 {
56 state_->active = true;
57 lock.unlock();
58 try
59 {
60 job();
61 job = {};
62 }
63 catch (...)
64 {
65 {
66 std::lock_guard<std::mutex> failed(state_->mutex);
67 state_->error = std::current_exception();
68 state_->closed = true;
69 state_->active = false;
70 }
71 state_->changed.notify_all();
72 throw;
73 }
74 lock.lock();
75 state_->active = false;
76 lock.unlock();
77 state_->changed.notify_all();
78 return;
79 }
80 if (!started_)
81 start();
82 state_->pending = std::move(job);
83 lock.unlock();
84 state_->changed.notify_all();
85 }
86
87 void flush()
88 {
89 std::unique_lock<std::mutex> lock(state_->mutex);
90 state_->changed.wait(lock, [&] { return (!state_->pending && !state_->active) || state_->error; });
92 }
93
94 void finish()
95 {
96 {
97 std::lock_guard<std::mutex> lock(state_->mutex);
98 state_->closed = true;
99 }
100 state_->changed.notify_all();
101 if (!asynchronous_)
102 {
103 std::unique_lock<std::mutex> lock(state_->mutex);
104 state_->changed.wait(lock, [&] { return !state_->active; });
105 }
106 if (thread_.joinable())
107 thread_.join();
108 std::lock_guard<std::mutex> lock(state_->mutex);
109 check_error();
110 }
111
112 bool asynchronous() const { return asynchronous_; }
113
114 void execute(const Job &compute)
115 {
116 const size_t threads = utils::get_n_threads();
117 if (threads <= 1 && !started_)
118 asynchronous_ = false;
119 if (!asynchronous_ || threads <= 1)
120 {
121 compute();
122 return;
123 }
124#ifdef POLYFEM_WITH_CPP_THREADS
125 utils::ScopedThreadLimit limit(threads - 1);
126 compute();
127#elif defined(POLYFEM_WITH_TBB)
128 tbb::task_arena simulation_arena(static_cast<int>(threads - 1));
129 simulation_arena.execute(compute);
130#else
131 compute();
132#endif
133 }
134
135 private:
136 struct State
137 {
138 std::mutex mutex;
139 std::condition_variable changed;
141 std::exception_ptr error;
142 bool active = false;
143 bool closed = false;
144 };
145
146 void check_error() const
147 {
148 if (state_->error)
149 std::rethrow_exception(state_->error);
150 }
151
152 static void run(const std::shared_ptr<State> &state)
153 {
154 utils::ScopedThreadLimit serial_output(1);
155 for (;;)
156 {
157 Job job;
158 {
159 std::unique_lock<std::mutex> lock(state->mutex);
160 state->changed.wait(lock, [&] { return state->pending || state->closed; });
161 if (!state->pending)
162 return;
163 job = std::exchange(state->pending, {});
164 state->active = true;
165 }
166 state->changed.notify_all();
167 try
168 {
169 job();
170 job = {};
171 }
172 catch (...)
173 {
174 Job discarded;
175 {
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, {});
181 }
182 state->changed.notify_all();
183 return;
184 }
185 {
186 std::lock_guard<std::mutex> lock(state->mutex);
187 state->active = false;
188 }
189 state->changed.notify_all();
190 }
191 }
192
193 void start()
194 {
195 // A blocking queue must not occupy a TBB scheduler worker while idle:
196 // other writers may need that worker to drain their queues.
197#if defined(POLYFEM_WITH_CPP_THREADS) || defined(POLYFEM_WITH_TBB)
198 thread_ = std::thread([state = state_] {
199#ifdef POLYFEM_WITH_TBB
200 tbb::task_arena output_arena(1);
201 output_arena.execute([&] { run(state); });
202#else
203 run(state);
204#endif
205 });
206#endif
207 started_ = true;
208 }
209
210 std::shared_ptr<State> state_ = std::make_shared<State>();
211 std::thread thread_;
212 bool asynchronous_ = false;
213 bool started_ = false;
214 };
215
216 OutputWriter::OutputWriter(const bool asynchronous) : impl_(std::make_unique<Impl>(asynchronous)) {}
217 OutputWriter::~OutputWriter() = default;
218 void OutputWriter::enqueue(const Prepare &prepare) { impl_->enqueue(prepare); }
219 void OutputWriter::execute(const Job &compute) { impl_->execute(compute); }
220 void OutputWriter::flush() { impl_->flush(); }
221 void OutputWriter::finish() { impl_->finish(); }
222 bool OutputWriter::asynchronous() const { return impl_->asynchronous(); }
223} // namespace polyfem::io
Impl(const bool asynchronous)
static void run(const std::shared_ptr< State > &state)
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.
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.
Definition par_for.hpp:20
size_t get_n_threads()
Definition par_for.hpp:71