5#ifdef ES_RENDER_THREADS
11#include <emscripten/emscripten.h>
12#include <emscripten/threading.h>
17thread_local RenderThread* RenderThread::current_ =
nullptr;
19RenderThread::~RenderThread() {
stop(); }
22 if (started_)
return true;
25 if (!emscripten_has_threading_support())
return false;
26 proxy_ = em_proxying_queue_create();
27 if (!proxy_)
return false;
29 pthread_attr_init(&attr);
30 if (canvas) emscripten_pthread_attr_settransferredcanvases(&attr, canvas);
31 const int error = pthread_create(&worker_, &attr, webEntry,
this);
32 pthread_attr_destroy(&attr);
34 em_proxying_queue_destroy(proxy_);
40 worker_ = std::thread([
this] {
42 std::unique_lock lock(mutex_);
44 changed_.wait(lock, [&] {
return stopping_ || !pending_.empty(); });
45 if (pending_.empty())
break;
46 auto command = std::move(pending_.front());
49 run(std::move(command));
59void RenderThread::run(Command command) {
64 std::lock_guard lock(mutex_);
65 completed_ = command.serial;
67 changed_.notify_all();
71void* RenderThread::webEntry(
void* arg) {
72 current_ =
static_cast<RenderThread*
>(arg);
75 emscripten_exit_with_live_runtime();
79void RenderThread::drainWeb(
void* arg) {
80 auto& self = *
static_cast<RenderThread*
>(arg);
81 std::deque<Command> batch;
83 std::lock_guard lock(self.mutex_);
84 batch.swap(self.pending_);
86 for (
auto& command : batch) self.run(std::move(command));
91 if (!started_) { work();
return 0; }
95 std::lock_guard lock(mutex_);
96 serial = ++submitted_;
98 const bool wake = pending_.empty();
100 pending_.push_back({serial, std::move(work)});
102 if (wake && !emscripten_proxy_async(proxy_, worker_, drainWeb,
this)) std::abort();
105 changed_.notify_all();
110 std::lock_guard lock(mutex_);
115 std::lock_guard lock(mutex_);
116 return completed_ >= value;
122 std::unique_lock lock(mutex_);
123 changed_.wait(lock, [&] {
return completed_ >= value; });
126void RenderThread::invokeChecked(std::function<
void()> work) {
127#ifdef __cpp_exceptions
128 std::exception_ptr error;
131 catch (...) { error = std::current_exception(); }
133 if (error) std::rethrow_exception(error);
142 wait(frames_[frameSlot_]);
143 frames_[frameSlot_] =
enqueue(std::move(end));
148 if (!started_)
return;
151 if (!emscripten_proxy_async(proxy_, worker_, [](
void*) { pthread_exit(
nullptr); },
nullptr)) std::abort();
152 pthread_join(worker_,
nullptr);
153 em_proxying_queue_destroy(proxy_);
157 std::lock_guard lock(mutex_);
160 changed_.notify_all();
bool complete(Fence value) const
Fence enqueue(std::function< void()> fn)
void finishFrame(std::function< void()> fn)
bool start(const char *=nullptr)
std::span< const EsCmd > run(SystemFn fn, std::span< const std::uint32_t > fallback, std::span< const QuerySpec > queries, std::span< void *const > resources, CallArena &arena, WorldStamp world={})