Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_312_MultiThread

Streaming data from a worker thread into a live viewer with a safe producer/consumer handoff.

Overview

This tutorial grows a point cloud while the viewer is running: a background worker thread generates batches of 100 random colored points every 300 ms, and the UI thread picks them up and appends them to the displayed cloud. It demonstrates the pattern every interactive application needs when computation and rendering run at different speeds — and the golden rule that makes it safe: only the UI thread ever touches scene or graphics state.

The technique

Graphics APIs (OpenGL contexts, Vulkan command submission) and Easy3D's scene structures are not thread-safe, so the classic mistake is letting a worker thread modify a model or drawable directly. The correct design is a producer/consumer pipeline: the worker (producer) computes plain CPU data — here immutable batches of positions and colors — and publishes them through a mutex-protected slot; the UI thread (consumer) takes a batch during its animation callback and applies it to the cloud, then refreshes the renderer so the new points appear. Ownership transfer via std::shared_ptr<const PointBatch> means no data is shared mutably: once published, a batch is read-only, and the consumer owns its copy. At most one batch may wait in the slot (backpressure): if the viewer is paused or minimized, the worker blocks instead of queueing unbounded data in memory. A condition_variable coordinates the handoff, and the worker's destructor signals shutdown and joins the thread before any viewer resource is destroyed — including when the user closes the window early.

Easy3D API

Running it

The cloud starts with 100 red points and gains 100 randomly colored points every ~300 ms (66 batches total); the point count is printed to the console. Press F2 to pause/resume consumption — while paused the worker waits instead of producing more. When all batches are consumed the animation stops automatically.

1
27#include <easy3d/viewer/viewer.h>
28#include <easy3d/core/point_cloud.h>
29#include <easy3d/core/random.h>
30#include <easy3d/renderer/renderer.h>
31#include <easy3d/renderer/drawable_points.h>
32#include <easy3d/util/initializer.h>
33#include "point_worker.h"
34
87using namespace easy3d;
88
89int main(int argc, char **argv) {
90 // initialize Easy3D.
91 initialize();
92
93 // create the viewer
94 Viewer viewer(EXAMPLE_TITLE);
95
96 // create a point cloud (with a per point color property) from a set of random points
97 auto cloud = new PointCloud;
98 // add a per point color property
99 auto colors = cloud->add_vertex_property<vec3>("v:color");
100 for (int i = 0; i < 100; ++i) {
101 auto v = cloud->add_vertex(easy3d::vec3(random_float(), random_float(), random_float()));
102 // assign a color to each point (here simply a red color)
103 colors[v] = vec3(1.0f, 0.0f, 0.0f);
104 }
105 // add the point cloud to the viewer for visualization
106 viewer.add_model(std::shared_ptr<PointCloud>(cloud));
107
108 // set up visualization parameters
109 auto drawable = cloud->renderer()->get_points_drawable("vertices");
110 // set point size
111 drawable->set_point_size(10.0f);
112 // set coloring method: we want to visualize the point cloud using the per point color property
113 drawable->set_coloring(Drawable::COLOR_PROPERTY, Drawable::VERTEX, "v:color");
114
115 // The worker owns its random generator and produces immutable CPU batches.
116 // One pending batch bounds memory if the viewer is paused or minimized.
117 // No worker ever reads or modifies the cloud, renderer or viewer.
118 // Constructing the worker starts its thread immediately.
119 PointBatchWorker worker;
120 // Block (bounded) until the first batch exists, so the demo never starts empty-handed.
121 // This wait is for startup only; the render loop below uses the nonblocking take().
122 if (!worker.wait_for_batch(std::chrono::seconds(5))) {
123 std::cerr << "point worker did not produce its first batch" << std::endl;
124 return EXIT_FAILURE;
125 }
126
127 // The consumer runs inside the viewer's animation callback — i.e. on the UI thread,
128 // the only thread allowed to mutate the cloud and its renderer.
129 viewer.animation_func_ = [&](Viewer *v) {
130 const auto batch = worker.take(); // nonblocking handoff to the UI thread
131 if (batch) {
132 // Append the points and refresh the portable geometry snapshot (see append_point_batch).
133 append_point_batch(*cloud, *batch);
134 v->update();
135 std::cout << "#points: " << cloud->n_vertices() << std::endl;
136 }
137 // All batches produced and consumed: stop the animation loop.
138 if (worker.drained())
139 v->set_animation(false);
140 return bool(batch);
141 };
142 viewer.set_animation(true); // F2 pauses/resumes consumption
143
144 // worker's destructor interrupts its waits and joins before viewer teardown,
145 // including early window closure and exceptions.
146 // (worker is declared after viewer, so C++ destroys it first — the thread is always
147 // joined while the viewer and cloud are still alive.)
148 return viewer.run();
149}
A data structure for point clouds.
Definition point_cloud.h:46
VertexProperty< T > add_vertex_property(const std::string &name, const T t=T())
Add a vertex property of type T with name name and default value t.
Definition point_cloud.h:489
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
Definition collider.cpp:182

The worker helper (producer/consumer implementation):

1
28#ifndef EASY3D_TUTORIAL_POINT_WORKER_H
29#define EASY3D_TUTORIAL_POINT_WORKER_H
30#include <easy3d/core/types.h>
31#include <easy3d/core/point_cloud.h>
32#include <easy3d/renderer/renderer.h>
33#include <chrono>
34#include <condition_variable>
35#include <exception>
36#include <memory>
37#include <mutex>
38#include <random>
39#include <stdexcept>
40#include <thread>
41#include <utility>
42#include <vector>
43
44
46struct ColoredPoint {
47 easy3d::vec3 position, color;
48};
49
51using PointBatch = std::vector<ColoredPoint>;
52
53// UI thread only: mutate scene state and invalidate drawable snapshots together.
54// This is the consumer's application step: it runs on the viewer thread (from the
55// animation callback), never on the worker, because PointCloud and Renderer are not
56// thread-safe and portable geometry snapshots must be refreshed from the thread that owns them.
57inline void append_point_batch(easy3d::PointCloud &cloud, const PointBatch &batch) {
58 auto colors = cloud.vertex_property<easy3d::vec3>("v:color");
59 for (const auto &point : batch)
60 colors[cloud.add_vertex(point.position)] = point.color;
61 // The cloud grew: rebuild the drawables' portable geometry snapshots so the new points render.
62 if (cloud.renderer())
63 cloud.renderer()->update();
64}
65
74// Worker-owned computation, with a single immutable batch waiting for the UI.
75// No Model, Renderer, Viewer or graphics API is accessed on the worker thread.
76class PointBatchWorker {
77public:
78 // Configure the number of batches and the pacing interval, then start the producer
79 // thread. The thread captures `this`, so the object must outlive it — stop() in the
80 // destructor enforces exactly that.
81 explicit PointBatchWorker(unsigned batches = 66,
82 std::chrono::milliseconds interval = std::chrono::milliseconds(300))
83 : batches_(batches), interval_(interval) {
84 if (interval.count() < 0)
85 throw std::invalid_argument("negative point batch interval");
86 thread_ = std::thread([this] {
87 produce();
88 });
89 }
90
91 // Always interrupt and join the worker before any member state is destroyed.
92 ~PointBatchWorker() {
93 stop();
94 }
95
96 // The worker owns a thread and a mutex: copying it would be meaningless and unsafe.
97 PointBatchWorker(const PointBatchWorker &) = delete;
98 PointBatchWorker &operator=(const PointBatchWorker &) = delete;
99
100 // Nonblocking UI-thread consumption; the returned batch owns its storage.
101 // Moving the shared_ptr out of the slot transfers ownership to the caller and frees
102 // the slot, which wakes the worker to produce the next batch.
103 std::shared_ptr<const PointBatch> take() {
104 std::lock_guard<std::mutex> lock(mutex_);
105 // Surface any worker failure on the UI thread instead of losing it silently.
106 if (error_)
107 std::rethrow_exception(error_);
108 auto result = std::move(pending_);
109 ready_.notify_all();
110 return result;
111 }
112
113 // Startup/tests only: ordinary rendering uses take() without waiting.
114 // Blocks up to `timeout` for the first publication (or shutdown/error).
115 bool wait_for_batch(std::chrono::milliseconds timeout) {
116 std::unique_lock<std::mutex> lock(mutex_);
117 ready_.wait_for(lock, timeout, [this] {
118 return pending_ || finished_ || stopping_ || error_;
119 });
120 if (error_)
121 std::rethrow_exception(error_);
122 return bool(pending_);
123 }
124
125 // Check completion and pending storage under the same lock, so a final
126 // publication cannot race with the UI deciding to pause consumption.
127 bool drained() const {
128 std::lock_guard<std::mutex> lock(mutex_);
129 return finished_ && !pending_;
130 }
131
132 // Called by the owner/UI thread. Interrupts both pacing and backpressure
133 // waits, and joins before any worker state or viewer resources can die.
134 void stop() {
135 {
136 std::lock_guard<std::mutex> lock(mutex_);
137 stopping_ = true;
138 }
139 // Wake every wait so the worker observes stopping_ promptly, then join.
140 ready_.notify_all();
141 if (thread_.joinable())
142 thread_.join();
143 }
144
145private:
146 // The producer loop, running entirely on the worker thread. It only touches plain
147 // CPU data and the shared slot — never the cloud, renderer, viewer, or graphics API.
148 void produce() noexcept {
149 try {
150 // Fixed seed: the demo is reproducible run to run.
151 std::mt19937 random(0x312);
152 std::uniform_real_distribution<float> unit(0, 1);
153 for (unsigned i = 0; i < batches_; ++i) {
154 {
155 // Backpressure: wait until the slot is empty (or we are told to stop).
156 // This bounds memory to one pending batch if the UI stops consuming.
157 std::unique_lock<std::mutex> lock(mutex_);
158 ready_.wait(lock, [this] {
159 return stopping_ || !pending_;
160 });
161 if (stopping_)
162 break;
163 }
164 // Generate the batch OUTSIDE the lock: computation never blocks the UI.
165 auto batch = std::make_shared<PointBatch>();
166 batch->reserve(100);
167 for (unsigned j = 0; j < 100; ++j) {
168 // Draw components separately for reproducible ordering in C++11.
169 const float x = unit(random), y = unit(random), z = unit(random);
170 const float r = unit(random), g = unit(random), b = unit(random);
171 batch->push_back({easy3d::vec3(x, y, z), easy3d::vec3(r, g, b)});
172 }
173 // Publish: hand the immutable batch to the slot and wake the consumer.
174 std::unique_lock<std::mutex> lock(mutex_);
175 if (stopping_)
176 break;
177 pending_ = std::move(batch);
178 ready_.notify_all();
179 // Pace the production; the timed wait doubles as an interruptible sleep
180 // (returns early with true if stopping_ was set).
181 if (i + 1 < batches_ && ready_.wait_for(lock, interval_, [this] {
182 return stopping_;
183 }))
184 break;
185 }
186 } catch (...) {
187 // Exceptions must not escape a thread entry point; store and rethrow on the UI side.
188 std::lock_guard<std::mutex> lock(mutex_);
189 error_ = std::current_exception();
190 }
191 {
192 std::lock_guard<std::mutex> lock(mutex_);
193 finished_ = true;
194 }
195 ready_.notify_all();
196 }
197
198 unsigned batches_;
199 std::chrono::milliseconds interval_;
200 mutable std::mutex mutex_;
201 std::condition_variable ready_;
202 std::shared_ptr<const PointBatch> pending_;
203 std::exception_ptr error_;
204 bool stopping_ = false, finished_ = false;
205 std::thread thread_;
206};
207
208#endif
Renderer * renderer()
Definition model.cpp:66
VertexProperty< T > vertex_property(const std::string &name, const T t=T())
Gets or adds a vertex property of type T with name name.
Definition point_cloud.h:540
void update()
Invalidates the rendering buffers of the model and thus updates the rendering (delayed in rendering).
Definition renderer.cpp:322
Vec< 3, float > vec3
A 3D point/vector of float type.
Definition types.h:44
Matrix< FT > random(int row, int col)
Generate a matrix with all its elements randomly initialized in the range [0.0, 1....
Definition matrix.h:1540
See also
Viewer, PointCloud, Renderer, PointsDrawable, Tutorial_311_Animation