如何用 kevent() 替换 select() 以获得更高的性能?
Kqueue 在内核之间提供高效的输入和输出事件管道和用户区。因此,可以修改事件过滤器以及接收待处理事件,同时每次主事件循环迭代仅使用对 kevent(2) 的单个系统调用。这与旧的传统轮询系统调用(例如 poll(2) 和 select(2))形成鲜明对比,后者效率较低,尤其是在轮询大量文件描述符上的事件时
这听起来不错。我的服务器以 FreeBSD 为目标,并且正在处理大量的网络套接字 fd - 对它们全部使用 select() 并确定从谁读取数据。我宁愿使用 kevent() 调用来获得更高的性能,因为这就是它的用途!
我在这里阅读了 FreeBSD 上 kevent 的 手册页 但这对我来说很神秘,而且我没有找到很好的资源来解释它。使用 kevent 替换 select 的示例可以解决我的问题,并且还可以帮助我更好地了解如何使用 kevent() 。
From the Kqueue Wikipedia Page:
Kqueue provides efficient input and output event pipelines between the kernel and userland. Thus, it is possible to modify event filters as well as receive pending events while using only a single system call to kevent(2) per main event loop iteration. This contrasts with older traditional polling system calls such as poll(2) and select(2) which are less efficient, especially when polling for events on a large number of file descriptors
That sounds great. I target FreeBSD for my server, and I'm handling a significant amount of network socket fd's - using a select() on them all and figuring out who to read data from. I'd rather use kevent() calls to get higher performance, since that's what it's there for!
I've read the man page for kevent on FreeBSD here but it's cryptic to me and I'm not finding good resources that explain it. An example of using kevent to replace select would solve my problem, and would also help me get a better idea of how kevent() is used.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,创建新的 kqueue:
现在在 kq 中注册您的 fd:
最后,等待数据到达您的套接字:
返回后,
res_kevs[i].ident
将包含您的套接字描述符,res_kevs [i].data
- 准备读取的字节数。有关更多详细信息和功能,请参阅 man kevent。
First, create new kqueue:
Now register your fd in kq:
Finally, wait for data to arrive into your socket:
After return,
res_kevs[i].ident
will contain your socket's descriptor,res_kevs[i].data
- number of bytes ready to be read.See man kevent for more details and features.
你通常做的是使用 libevent 它会为你处理所有细节,并且还意味着您可以将程序转移到另一个具有不同方案(例如 Linux 和 epoll)的操作系统来执行类似的操作。
What you do normally, is use libevent, which takes care of all the details for you, and also means that you can move your program on to another OS which has a different scheme (e.g. Linux and epoll) for doing something similar.