用 C 语言编写异步事件服务器的推荐模式
我正在用 C 语言编写第一个单线程、单进程服务器,使用 kqueue() / epoll() 来处理异步事件调度。正如人们所预料的那样,遵循控制流比在阻塞服务器中要困难得多。
人们是否有一个通用的模式(甚至可能有一个名字)来避免回调驱动的协议实现变成一个巨大的纠结毛团?
或者,是否有任何用 C 语言编写的非阻塞服务器,其源代码阅读起来很愉快?
任何意见将不胜感激!
更多想法:
很多问题似乎来自于处理 IO 缓冲的需要。缓冲区填充/排出和单个状态转换之间没有必然的对应关系。缓冲区填充/排出可能对应于 [0, N] 状态转换。)
我研究过 libev (docs here),它看起来是一个很棒的工具,而 libevent 看起来不那么令人兴奋,但仍然有用,但它们都没有真正回答这个问题:我如何管理控制流的方式不是非常不透明。
I am writing my first single-threaded, single-process server in C using kqueue() / epoll() to handle asynchronous event dispatch. As one would expect, it is quite a lot harder to follow the flow of control than in a blocking server.
Is there a common pattern (maybe even with a name) that people use to avoid the callback-driven protocol implementation becoming a gigantic tangled hairball?
Alternately, are there any nonblocking servers written in C for which the source code is a pleasure to read?
Any input would be much appreciated!
More thoughts:
A lot of the cruft seems to come from the need to deal with the buffering of IO. There is no necessary correspondence between a buffer filling/draining and a single state transition. A buffer fill/drain might correspond to [0, N] state transitions.)
I've looked at libev (docs here) and it looks like a great tool, and libevent, which looks less exciting but still useful, but neither of them really answers the question: how do I manage the flow of control in a way that isn't horrendously opaque.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用 状态线程 或 GNU 可移植线程,它允许您像每个连接使用单个线程一样编写(实现使用 光纤)。
或者,您可以使用状态机生成器(例如 Ragel)构建协议实现。
You can try using something like State Threads or GNU Portable Threads, which allows you to write as though you were using a single thread per connection (The implementation uses Fibers).
Alternately, you can build your protocol implementation using a state machine generator (such as Ragel).