选择/轮询循环中的回调和延迟 [英] Callbacks and Delays in a select/poll loop
问题描述
编写服务器时可以使用轮询/选择,该服务器可以为同一线程中的多个客户端提供服务.选择并轮询,但是需要文件描述符才能工作.因此,我不确定如何执行简单的异步操作,例如实现简单的回调以中断长时间运行的操作或延迟的回调而不退出select/poll循环.如何做到这一点?理想情况下,我想这样做而不求助于生成新线程.
简而言之,我正在寻找一种可以执行所有异步操作的机制. WindowsWaitForMultipleObjects
或Symbian TRequestStatus
似乎更适合于通用异步操作.对于任意回调,请维护POSIX管道(请参见pipe(2)).当您要进行延迟调用时,请在写入端编写一个由函数指针和可选上下文指针组成的结构.读取端只是可供选择的另一个输入.如果选择可读,则读取相同的结构,并以上下文作为参数调用该函数.
对于定时回调,请按到期时间顺序维护列表.列表中的条目是例如{到期时间(以上一次回调为间隔);功能指针;可选的上下文指针}.如果此列表为空,请在select()中永久阻止.否则,在第一个事件到期时超时.在每次调用选择之前,请重新计算第一个事件的到期时间.
将详细信息隐藏在合理的界面后面.
One can use poll/select when writing a server that can service multiple clients all in the same thread. select and poll, however need a file descriptor to work. For this reason, I am uncertain how to perform simple asynchronous operations, like implementing a simple callback to break up a long running operation or a delayed callback without exiting the select/poll loop. How does one go about doing this? Ideally, I would like to do this without resorting to spawning new threads.
In a nutshell, I am looking for a mechanism with which I can perform ALL asynchronous operations. The windows WaitForMultipleObjects
or Symbian TRequestStatus
seems a much more suited to generalized asynchronous operations.
For arbitrary callbacks, maintain a POSIX pipe (see pipe(2)). When you want to do a deferred call, write a struct consisting of a function pointer and optional context pointer to the write end. The read end is just another input for select. If it selects readable, read the same struct, and call the function with the context as argument.
For timed callbacks, maintain a list in order of due time. Entries in the list are structs of e.g. { due time (as interval since previous callback); function pointer; optional context pointer }. If this list is empty, block forever in select(). Otherwise, timeout when the first event is due. Before each call to select, recalculate the first event's due time.
Hide the details behind a reasonable interface.
这篇关于选择/轮询循环中的回调和延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!