@@ -19,6 +19,9 @@ NodeIntegration::NodeIntegration()
1919 embed_closed_ (false ) {
2020}
2121
22+ constexpr uint64_t EVENT_BATCH_TIMEOUT_MS = 8 ;
23+ constexpr int EVENT_BATCH_SIZE = 16 ;
24+
2225NodeIntegration::~NodeIntegration () {
2326 // Quit the embed thread.
2427 embed_closed_ = true ;
@@ -63,9 +66,6 @@ void NodeIntegration::UvRunOnce() {
6366
6467 // Deal with uv events.
6568 uv_run (uv_loop_, UV_RUN_NOWAIT);
66-
67- // Tell the worker thread to continue polling.
68- uv_sem_post (&embed_sem_);
6969}
7070
7171void NodeIntegration::CallNextTick () {
@@ -79,6 +79,19 @@ void NodeIntegration::ReleaseHandleRef() {
7979void NodeIntegration::WakeupMainThread () {
8080 PostTask ([this ] {
8181 this ->UvRunOnce ();
82+ // ^ This also updates the uv_now() timestamp.
83+ uint64_t start_time_ms = uv_now (uv_loop_);
84+
85+ int loop_count = EVENT_BATCH_SIZE;
86+ uint64_t elapsed_ms = 0 ;
87+ while (loop_count != 0 && (elapsed_ms < EVENT_BATCH_TIMEOUT_MS)) {
88+ loop_count--;
89+ this ->UvRunOnce ();
90+ elapsed_ms = uv_now (uv_loop_) - start_time_ms;
91+ }
92+
93+ // Tell the worker thread to continue polling.
94+ uv_sem_post (&this ->embed_sem_ );
8295 });
8396}
8497
@@ -91,8 +104,6 @@ void NodeIntegration::EmbedThreadRunner(void *arg) {
91104 NodeIntegration* self = static_cast <NodeIntegration*>(arg);
92105
93106 while (true ) {
94- // Wait for the main loop to deal with events.
95- uv_sem_wait (&self->embed_sem_ );
96107 if (self->embed_closed_ )
97108 break ;
98109
@@ -113,6 +124,9 @@ void NodeIntegration::EmbedThreadRunner(void *arg) {
113124
114125 // Deal with event in main thread.
115126 self->WakeupMainThread ();
127+
128+ // Wait for the main loop to deal with events.
129+ uv_sem_wait (&self->embed_sem_ );
116130 }
117131}
118132
0 commit comments