·understanding-kqueue
Understanding kqueue
A practical introduction to event-driven I/O on macOS.
- networking
- c
- macos
Understanding kqueue
When working with network servers, one of the first problems you encounter is handling multiple connections efficiently.
A naive server might create a thread for every connection. That works, but it doesn't scale particularly well.
This is where event-driven I/O becomes useful.
The basic idea
Instead of constantly asking every socket whether something happened, we register our interest in events and wait until the operating system tells us that something changed.
On macOS, one of the mechanisms for doing this is kqueue.
int kq = kqueue();
struct kevent event;
EV_SET(
&event,
socket_fd,
EVFILT_READ,
EV_ADD,
0,
0,
NULL
);