I/O 完成端口,如何释放每个套接字上下文和每个 I/O 上下文?
我在 UDP 套接字上使用 IOCP,并且 UDP 套接字可能在另一个线程中关闭。 那么,如何安全地释放与 SOCKET 关联的 Per Socket Context 和 Per I/O Context 呢?
当我关闭套接字时,内核队列中仍然会有未完成的 I/O 请求。
如果我在套接字关闭时释放上下文,则 GetQueueCompletionStatus 可能会失败。
现在,我的问题是何时释放上下文?
I'm using IOCP on UDP socket, and the UDP socket may be closed in another thread. So, how can I free Per Socket Context and Per I/O Context which associated with SOCKET safely?
When I close the socket, there will still be un-completed I/O request in kernel queue.
If I free context just when socket closed, the GetQueueCompletionStatus may failed.
Now, my question is when to free context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对所有每个套接字和每个 I/O 数据结构使用引用计数。 它使这种事情变得很容易,因为当它们的引用下降到 0 时,它们就会被删除。有关显示一种方法的示例代码,您可以查看我的免费 IOCP 框架,您可以从 此处。
I use reference counting on all of my per socket and per I/O data structures. It makes this kind of thing easy as they are deleted when their references drop to 0. For some example code which shows one way to do this you could take a look at my free IOCP framework which you can download from here.
使用 互斥体 在代码的关键部分强制执行互斥,以检查互斥体的可用性插座,并在必要时打开它。 将套接字锁定到该线程,并在完成后适当地释放它。
Use a mutex to enforce mutual exclusion in a critical section of your code that will check the availability of the socket, and open it if necessary. Lock the socket to that thread, and release it appropriately when finished.
我重用了每个套接字的结构。 在收到该连接所需的所有读写操作的完成事件后,我调用
TransmitFile
带有TF_DISCONNECT
和TF_REUSE_SOCKET
标志来重置套接字,而无需关闭它。 一旦 TransmitFile 调用的完成事件完成,我还会重置每个连接的数据。I reuse my per-socket structures. After I have received completion events for all of the read and write operations that are required for that connection, I call
TransmitFile
with theTF_DISCONNECT
andTF_REUSE_SOCKET
flags to reset the socket without having to close it. I also reset the per-connection data once the completion event for theTransmitFile
call comes through.首先关闭套接字。 您将从 GetQueuedCompletionStatus 收到错误(我认为是 ERROR_OPERATION_ABORTED),然后是释放该结构的正确时间。 此时内核队列中该连接上已没有其他未完成的请求,完成数据包按 FIFO 顺序维护,错误数据包肯定是该连接的最后一个数据包。
Close the socket first. You will get error (I think it is ERROR_OPERATION_ABORTED) from GetQueuedCompletionStatus, and then it is right time to free the structure. There are no other uncompleted requests on this connection in kernel queue by then, completion packets are maintained in FIFO order, and error packet will definitely be the last one for this connection.