@@ -62,6 +62,35 @@ void script_context::bind() {
6262}
6363script_context::script_context () : rt{}, js{} {}
6464
65+ void script_context::run_event_loop () {
66+ while (!should_stop.load ()) {
67+ while (js->pending_job_count .load () > 0 ) {
68+ std::unique_lock lock (js->js_mutex );
69+ auto ctx = js->ctx ;
70+ if (auto res = JS_ExecutePendingJob (rt->rt , &ctx); res < 0 ) {
71+ std::cerr << " Error executing pending JS job: " ;
72+ auto val = qjs::Value{js->ctx , JS_GetException (js->ctx )};
73+ std::cerr << (std::string)val << (std::string)val[" stack" ]
74+ << std::endl;
75+ }
76+ lock.unlock ();
77+ js->pending_job_count .fetch_sub (1 );
78+ std::this_thread::yield ();
79+ }
80+ js->pending_job_count .wait (0 );
81+ if (js->pending_job_count .load () == -1 )
82+ break ;
83+ }
84+ }
85+
86+ void script_context::stop () {
87+ should_stop.store (true );
88+ if (js) {
89+ js->pending_job_count .exchange (-1 );
90+ js->pending_job_count .notify_all ();
91+ }
92+ }
93+
6594class WindowsThreadWrapper {
6695private:
6796 HANDLE hThread_;
@@ -109,10 +138,10 @@ void script_context::watch_folder(const std::filesystem::path &path,
109138 spdlog::info (" Reloading all scripts" );
110139
111140 if (js) {
112- js->pending_job_count .exchange (-1 );
113- js->pending_job_count .notify_all ();
141+ stop ();
114142 if (js_thread)
115143 js_thread->join ();
144+ should_stop.store (false );
116145 js->pending_job_count .exchange (0 );
117146 }
118147
@@ -250,27 +279,7 @@ void script_context::watch_folder(const std::filesystem::path &path,
250279 is_js_ready.exchange (true );
251280 is_js_ready.notify_all ();
252281
253- while (true ) {
254- while (js->pending_job_count .load () > 0 ) {
255- std::unique_lock lock (js->js_mutex );
256- auto ctx = js->ctx ;
257- if (auto res = JS_ExecutePendingJob (rt->rt , &ctx);
258- res < 0 ) {
259- std::cerr << " Error executing pending JS job: " ;
260- auto val = qjs::Value{js->ctx ,
261- JS_GetException (js->ctx )};
262- std::cerr << (std::string)val
263- << (std::string)val[" stack" ]
264- << std::endl;
265- }
266- lock.unlock ();
267- js->pending_job_count .fetch_sub (1 );
268- std::this_thread::yield ();
269- }
270- js->pending_job_count .wait (0 );
271- if (js->pending_job_count .load () == -1 )
272- break ;
273- }
282+ run_event_loop ();
274283 is_thread_js_main = false ;
275284 } catch (std::exception &e) {
276285 std::cerr << " Fatal error in JS thread: " << e.what ()
@@ -293,7 +302,7 @@ void script_context::watch_folder(const std::filesystem::path &path,
293302 has_update = true ;
294303 });
295304
296- while (true ) {
305+ while (!should_stop. load () ) {
297306 std::this_thread::sleep_for (std::chrono::milliseconds (300 ));
298307 if (has_update && on_reload ()) {
299308 has_update = false ;
0 commit comments