Event Loop
Agenda
- What is the event loop
- Is NodeJS single-threaded or multi-threaded
Let the code explain.
int server = socket();
bind(server, 80);
listen(server)
int server = socket();
bind(server, 80);
listen(server)
while(int connection = accept(server)) {
pthread_create(echo, connection)
}
while(int connection = accept(server)) {
pthread_create(echo, connection)
}
void echo(int connection) {
char buf[4096];
while(int size = read(connection, buffer, sizeof buf)) {
write(connection, buffer, size)
}
}
epoll
epoll is a Linux kernel system call for a scalable I/O event notification mechanism, first introduced in version 2.5.44 of the Linux kernel mainline. Its function is to monitor multiple file descriptors to see whether I/O is possible on any of them.
int server = ... //like before
int eventdf = epoll_create1(0);
struct epoll_event ev = {.events = EPOLLIN, .data.fd = server};
epoll_ctl(epollfd, EPOL_CTL_ADD, server, &ev);
while((int max = epoll_wait(eventsfd, events, 10))) {
....
}
struct epoll_events events[10];
while((int max = epoll_wait(eventsfd, events, 10))) {
for(int n=0; n < max ; n++) {
if(events[n].data.fd.fd == server) {
//Server has socket connection
int connection = accept(server);
ev.events = EPOLLIN;
ev.data.fd = connection;
epoll_ctl(eventfd, EPOLL_CTL_ADD, connection, &ev);
}
}
}
while((int max = epoll_wait(eventsfd, events, 10))) {
for(int n=0; n < max ; n++) {
if(events[n].data.fd.fd == server) {
//Server has socket connection
int connection = accept(server);
ev.events = EPOLLIN;
ev.data.fd = connection;
epoll_ctl(eventfd, EPOLL_CTL_ADD, connection, &ev);
}
else {
char buf[4096];
while(int size = read(connection, buffer, sizeof buf)) {
write(connection, buffer, size);
}
}
}
}
NodeJS EventLoop
A semi infinite while loop, polling and blocking the OS untill some of the descriptors are ready.
Whats epoll-able in NodeJS?
Pollable | Time | Everything Else |
---|---|---|
can be directly waited upon | can be directly waited upon | must happen off loop and signal back to the loop when done |
sockets (net, http, dgram) etc. |
timeouts and intervals | Everything in fs.* uses the uv threadpool |
Uv Thread Pool
-
fs
- dns (some APIs)
- crypto (some APIs)
- http.get()/requestÂ
- any C++ addons
Shared by
Default number of threads is 4
Event Loop
By Minhaj Khan
Event Loop
- 166