Event Loop Source Code
Event Loop Phases
Event Loop Phases Source Code Structure:
// src/node.cc
void NodeMainInstance::Run() {
// ...
while (uv_run(uv_default_loop(), UV_RUN_DEFAULT) != 0) {
// Process each phase of the event loop
ProcessTimers(); // Timers phase
ProcessPendingCallbacks(); // Pending Callbacks phase
ProcessIdleCallbacks(); // Idle/Prepare phase
ProcessPollEvents(); // Poll phase
ProcessCheckCallbacks(); // Check phase
ProcessCloseCallbacks(); // Close Callbacks phase
}
// ...
}
// Specific phase implementations
void ProcessTimers() {
// Execute setTimeout/setInterval callbacks
uv_run(uv_default_loop(), UV_RUN_NOWAIT); // Simplified example
}
void ProcessPendingCallbacks() {
// Execute system-level operation callbacks (e.g., TCP errors)
}
void ProcessPollEvents() {
// Retrieve new I/O events and execute callbacks
int timeout = CalculatePollTimeout();
uv_run(uv_default_loop(), UV_RUN_ONCE); // Simplified example
}Phase Execution Order:
- Timers Phase: Executes setTimeout and setInterval callbacks
- Pending Callbacks Phase: Executes system-level operation callbacks
- Idle/Prepare Phase: Internal use
- Poll Phase: Retrieves new I/O events
- Check Phase: Executes setImmediate callbacks
- Close Callbacks Phase: Executes callbacks for close events
Callback Queue Management and Execution
Callback Queue Source Code Implementation:
// src/async_wrap.cc
class AsyncCallbackQueue {
public:
void Push(Callback* cb) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push_back(cb);
}
Callback* Pop() {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) return nullptr;
auto cb = queue_.front();
queue_.pop_front();
return cb;
}
private:
std::mutex mutex_;
std::deque<Callback*> queue_;
};
// Execute callbacks in the event loop
void ExecuteCallbacks(AsyncCallbackQueue* queue) {
while (Callback* cb = queue->Pop()) {
cb->Run();
}
}Microtask Queue Implementation:
// src/v8_platform.cc
class MicrotaskQueue {
public:
void Add(v8::Microtask* task) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push_back(task);
}
void Run(v8::Isolate* isolate) {
std::vector<v8::Microtask*> tasks;
{
std::lock_guard<std::mutex> lock(mutex_);
tasks.swap(queue_);
}
for (auto task : tasks) {
task->Run(isolate);
}
}
private:
std::mutex mutex_;
std::vector<v8::Microtask*> queue_;
};Microtask and Macrotask Scheduling
Microtask Scheduling Source Code:
// src/v8_platform.cc
void V8Platform::RunMicrotasks(v8::Isolate* isolate) {
// Get microtask queue
MicrotaskQueue* queue = GetMicrotaskQueue(isolate);
// Execute all microtasks
queue->Run(isolate);
}
// Call microtasks in the event loop
void ProcessMicrotasks() {
v8::Isolate* isolate = GetCurrentIsolate();
V8Platform::GetInstance()->RunMicrotasks(isolate);
}Macro and Microtask Interaction:
// Example: Interaction between setTimeout and Promise
setTimeout(() => {
console.log('setTimeout'); // Macrotask
}, 0);
Promise.resolve().then(() => {
console.log('Promise'); // Microtask
});
// Execution order:
// 1. Promise microtask
// 2. setTimeout macrotaskEvent Loop Performance Optimization
Performance Optimization Strategies:
// src/node.cc
void OptimizeEventLoop() {
// 1. Adjust UV_THREADPOOL_SIZE
uv_threadpool_size(8); // Adjust based on CPU cores
// 2. Reduce timer count
Cleanup();
// 3. Optimize Poll phase
AdjustPollTimeout();
// 4. Reduce context switching
BatchProcessCallbacks();
}
void AdjustPollTimeout() {
// Dynamically calculate Poll phase timeout
int timeout = CalculateOptimalTimeout();
uv_backend_timeout(uv_default_loop()) = timeout;
}Batch Callback Processing Optimization:
// src/async_wrap.cc
void BatchProcessCallbacks(AsyncCallbackQueue* queue) {
const int BATCH_SIZE = 100;
std::vector<Callback*> batch;
while (Callback* cb = queue->Pop()) {
batch.push_back(cb);
if (batch.size() >= BATCH_SIZE) {
ExecuteBatch(batch);
batch.clear();
}
}
if (!batch.empty()) {
ExecuteBatch(batch);
}
}Event Loop Debugging and Analysis
Debugging Tool Implementation:
// src/debug_utils.cc
class EventLoopDebugger {
public:
void Start() {
uv_loop_t* loop = uv_default_loop();
uv_walk(loop, OnWalkHandle, this);
}
static void OnWalkHandle(uv_handle_t* handle, void* arg) {
EventLoopDebugger* debugger = static_cast<EventLoopDebugger*>(arg);
debugger->RecordHandle(handle);
}
void RecordHandle(uv_handle_t* handle) {
handles_.push_back(handle);
}
void DumpStats() {
printf("Event Loop Handles:\n");
for (auto handle : handles_) {
printf("- %s\n", GetHandleType(handle));
}
}
private:
std::vector<uv_handle_t*> handles_;
};
// Example usage
EventLoopDebugger debugger;
debugger.Start();
debugger.DumpStats();Performance Analysis Tool:
// src/perf_utils.cc
class EventLoopProfiler {
public:
void Start() {
start_time_ = uv_hrtime();
}
void Stop() {
uint64_t end_time = uv_hrtime();
uint64_t duration = end_time - start_time_;
printf("Event Loop Duration: %llu ns\n", duration);
}
private:
uint64_t start_time_;
};



