用非IO事件中断epoll_wait,没有信号
当前场景是 epoll_wait 超过几个 fd 和一个可能传入消息的队列,我希望 epoll_wait 下面的循环在 IO 事件或新消息上执行。
我知道的方法:
上面发布的点都不足以让我满意,我想知道是否有我还没有找到任何其他方法。
原因是:
- 信号是多线程代码中需要避免的东西,而且不是很可靠
- 超时会消除 epoll 的部分好处,只能通过事件唤醒
- 自管道技巧看起来是目前最好的方法,但仍然有太多的样板
想法?
Current scenario is epoll_wait over a couple of fds and a queue of possible incoming messages, I'd like the loop below epoll_wait to be executed on IO event or on new message.
Ways I know:
- Use a
time
msec timeout and check the queue first thing in the loop - Use the self-pipe trick from the queue code when messages become available
- Interrupt the syscall with a standard signal
- Use epoll_pwait and refine the previous point
None of the points posted above satisfy me enough and I was wondering if there are any other methods that I haven't found.
Reasons are:
- Signals are something to avoid on multithreaded code and are not very reliable
- Timeout one removes part of the benefit of the epoll, only waking with events
- Self-pipe trick looks the best approach for the moment, but still too much boilerplate
ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 eventfd 这是实际上与自管道技巧相同,只是文件描述符和样板文件更少(例如 glibc 具有方便的 eventfd_read/write 函数)。
You can use an eventfd which is effectively the same thing as the self-pipe trick except with fewer file descriptors and less boilerplate (glibc has convenience
eventfd_read/write
functions for instance).您已经枚举了可以唤醒 epoll 的事件,因此问题实际上变成了:“如何减少自管道技巧的样板?”
这个问题的答案实际上取决于您的代码、语言以及您想要做什么。我假设您有一个处理 I/O 的线程,并且您希望在没有 I/O 准备就绪时在该线程中执行其他工作。在管理 epoll 循环的代码中,它可以有一个内部句柄,该句柄作为“唤醒”函数或“提交工作”函数暴露给系统的其他部分。
有一些库可以执行此操作,例如用于 C++ 的 boost.asio。然而,如果您只是针对 epoll,那么编写自己的代码并不困难,并且一旦您拥有处理 epoll 循环的类/模块/任何内容,实际的样板代码量应该是最少的。
You have enumerated the events that can wake up epoll, so the question really becomes: "How do I reduce the boilerplate for the self-pipe trick?"
The answer to that question really depends on your code, the language and what you are trying to do. I assume you have a thread that processes I/O and you want to do other work in that thread while there is no I/O ready. In the code that manages the epoll loop, it can have an internal handle that is exposed to other parts of the system as a "wake" function or a "submit work" function.
There are libraries that do this, for example boost.asio for C++. However, it isn't difficult to write your own if you're just targeting epoll, and the amount of actual boilerplate code should be minimal once you have a class/module/whatever that deals with the epoll loop.