如何用kevent()替换select()以获得更高的性能? [英] How do I replace select() with kevent() for higher performance?

查看:192
本文介绍了如何用kevent()替换select()以获得更高的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kqueue Wikipedia页面:

Kqueue在内核和用户域之间提供了有效的输入和输出事件管道.因此,可以在每次主事件循环迭代中仅使用对kevent(2)的单个系统调用时修改事件过滤器以及接收未决事件.这与效率较低的传统传统轮询系统调用(例如poll(2)和select(2))形成对比,尤其是在轮询大量文件描述符上的事件时

听起来不错.我将FreeBSD定位为服务器,并且正在处理大量的网络套接字fd-对它们全部使用select()并弄清楚谁可以读取数据.我宁愿使用kevent()调用来获得更高的性能,因为这就是它的作用!

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!

我已阅读有关kevent的手册页在这里的FreeBSD上,但这对我来说是个谜,我找不到很好的资源来解释它.使用kevent代替select的示例可以解决我的问题,也可以帮助我更好地了解如何使用kevent().

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.

推荐答案

首先,创建新的kqueue:

First, create new kqueue:

int kq=kqueue();

现在在kq中注册您的fd:

Now register your fd in kq:

struct kevent kev;
kev.ident=your_fd;
kev.flags=EV_ADD | EV_CLEAR;
kev.filter=EVFILT_READ;
kev.fflags=0;
kev.data=0;
kev.udata=&your_data;

int res=kevent(kq,&kev,1,0,0,0);

最后,等待数据到达您的套接字:

Finally, wait for data to arrive into your socket:

struct kevent res_kevs[5];
int res=kevent(kq,0,0,res_kevs,5,0);

返回后,res_kevs[i].ident将包含套接字的描述符,res_kevs[i].data-准备读取的字节数.

After return, res_kevs[i].ident will contain your socket's descriptor, res_kevs[i].data - number of bytes ready to be read.

有关更多详细信息和功能,请参见man kevent.

See man kevent for more details and features.

这篇关于如何用kevent()替换select()以获得更高的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆