收藏 分享(赏)

第三章_overlappedIO.ppt

上传人:j35w19 文档编号:8222037 上传时间:2019-06-15 格式:PPT 页数:28 大小:429.50KB
下载 相关 举报
第三章_overlappedIO.ppt_第1页
第1页 / 共28页
第三章_overlappedIO.ppt_第2页
第2页 / 共28页
第三章_overlappedIO.ppt_第3页
第3页 / 共28页
第三章_overlappedIO.ppt_第4页
第4页 / 共28页
第三章_overlappedIO.ppt_第5页
第5页 / 共28页
点击查看更多>>
资源描述

1、重叠IO模型,Prepared by Shing (Remark: Modified by Zero),2种类型,Overlapped IO 事件通知模型 后来,微软通过调查发现,老陈不喜欢上下楼收发信件,因为上下楼其实很浪费时间。于是微软再次改进他们的信箱。新式的信箱采用了更为先进的技术,只要用户告诉微软自己的家在几楼几号,新式信箱会把信件直接传送到用户的家中,然后告诉用户,你的信件已经放到你的家中了!老陈很高兴,因为他不必再亲自收发信件了! Overlapped IO 完成例程模型 老陈接收到新的信件后,一般的程序是:打开信封-掏出信纸 -阅读信件-回复信件 为了进一步减轻用户负担,微软又

2、开发了一种新的技术:用户只要告诉微软对信件的操作步骤,微软信箱将按照这些步骤去处理信件,不再需要用户亲自拆信 /阅读/回复了!老陈终于过上了小资生活!,Outline,Traditional Blocking I/O Overlapped I/O Event Object Signaling Alertable I/O,Traditional Blocking I/O,Time Required = A + B + C + D,Max Rate = Packet Size / Time Required,Overlapped I/O,When using overlapped I/O, the

3、 I/O operation will run in the background While the I/O operation runs in the background, the application can do some other processing When the I/O operation completes, the application is notified There are multiple mechanisms for notifying the application that an I/O operation has been completed: E

4、vent Object Signaling Alertable I/O,Overlapped I/O,Advantages Non-blocking Use application buffers to receive data directlyAllow posting multiple receive calls,Overlapped I/O Create Overlapped Socket,Use WSASocket() instead of socket() Use normal bind(), accept(), connect() etc,Overlapped I/O Send &

5、 Receive Data,For TCP, use WSASend() WSARecv() For UDP, use WSASendTo() WSARecvFrom(),Overlapped I/O Receive,Important parameters for WSARecv and WSARecvFrom: Socket Array of WSABUF structures Number of elements in WSABUF array WSAOVERLAPPED structure Pointer to I/O completion routine (used for aler

6、table I/O),Overlapped I/O Receive,The return value Does not return the number of bytes received. Only tell you it success or error. SOCKET_ERROR may be returned even there was no error. Use WSAGetLastError() to check, if error code is WSA_IO_PENDING, it means there is no error!,Overlapped I/O WSABUF

7、,The definition of buffer for overlapped I/Olen The length of buffer Have to be filled in advance buf The memory space that actually hold the data,typedef struct _WSABUF u_long len; char FAR* buf; WSABUF, *LPWSABUF;,Overlapped I/O WSAOVERLAPPED structure,A mean for notification,typedef struct _WSAOV

8、ERLAPPED DWORD Internal; DWORD InternalHigh; DWORD Offset; DWORD OffsetHigh; WSAEVENT hEvent; WSAOVERLAPPED, *LPWSAOVERLAPPED;,hEvent Function call returns immediately, some mechanisms are needed to determine the status and the completion of the request Used in event object notification,Overlapped I

9、/O The Model - Use of Event Object,Need to Figure Out which Buffer is Being Filled (or Returned),Overlapped I/O Event Object Notification,Create an event objectSimilar to Mutex and Semaphore, event objects also have signaled or nonsignaled state Pass this object to hEvent of the WSAOVERLAPPED struct

10、ure To know when the I/O operation complete WSAWaitForMultipleEvents() To retrieve the results of overlapped operations WSAGetOverlappedResult() Reset the event object to nonsignaled state WSAResetEvent() To free resources occupied by the event object WSACloseEvent(),WSAEVENT WSACreateEvent(void);,实

11、例,1./ write by larry 2./ 2009-8-20 3./ This is a server using overlapped IO(event notify). 4.#include “stdafx.h“ 5.#include 6.#include 7.#pragma comment(lib, “ws2_32.lib“) 8.#define PORT 5150 9.#define MSGSIZE 1024 10.typedef struct 11. 12. WSAOVERLAPPED overlap; 13. WSABUF Buffer; 14. char szMessag

12、eMSGSIZE; 15. DWORD NumberOfBytesRecvd; 16. DWORD Flags; 17. PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA; 18.int g_iTotalConn = 0; 19.SOCKET g_CliSocketArrMAXIMUM_WAIT_OBJECTS; 20.WSAEVENT g_CliEventArrMAXIMUM_WAIT_OBJECTS; 21.LPPER_IO_OPERATION_DATA g_pPerIoDataArrMAXIMUM_WAIT_OBJECTS; 22.DWORD

13、 WINAPI WorkerThread(LPVOID lpParam); 23.void Cleanup(int index); 24.,代码结构存在什么问题? 代码哪些可以优化?,25.int main(int argc, char* argv) 26. 27. WSADATA wsaData; 28. SOCKET sListen, sClient; 29. SOCKADDR_IN local, client; 30. DWORD dwThreadId; 31. int iAddrSize = sizeof(SOCKADDR_IN); 32. / Initialize windows s

14、ocket library 33. WSAStartup(0x0202, ,45. while (TRUE) 46. 47. / Accept a connection 48. sClient = accept(sListen, (sockaddr*) 73.,74.DWORD WINAPI WorkerThread(LPVOID lpParam) 75. 76. int ret, index; 77. DWORD cbTransferred; 78. while (TRUE) 79. 80. ret = WSAWaitForMultipleEvents(g_iTotalConn, g_Cli

15、EventArr, FALSE, 1000, FALSE); 81. if (ret = WSA_WAIT_FAILED | ret = WSA_WAIT_TIMEOUT) 82. 83. continue; 84. 85. index = ret - WSA_WAIT_EVENT_0; 86. WSAResetEvent(g_CliEventArrindex); 87. WSAGetOverlappedResult(g_CliSocketArrindex, 88. ,92. if (cbTransferred = 0) 93. 94. / The connection was closed

16、by client 95. Cleanup(index); 96. 97. else 98. 99. / g_pPerIoDataArrindex-szMessage contains the recvived data 100. g_pPerIoDataArrindex-szMessagecbTransferred = 0; 101. send(g_CliSocketArrindex, g_pPerIoDataArrindex-szMessage, cbTransferred, 0); 102. / Launch another asynchronous operation 103. WSA

17、Recv(g_CliSocketArrindex, 104. 114.,115.void Cleanup(int index) 116. 117. closesocket(g_CliSocketArrindex); 118. WSACloseEvent(g_CliEventArrindex); 119. HeapFree(GetProcessHeap(), 0, g_pPerIoDataArrindex); 120. if (index g_iTotalConn-1) 121. 122. g_CliSocketArrindex = g_CliSocketArrg_iTotalConn-1; 1

18、23. g_CliEventArrindex = g_CliEventArrg_iTotalConn-1; 124. g_pPerIoDataArrindex = g_pPerIoDataArrg_iTotalConn-1; 125. 126. 127. g_pPerIoDataArr-g_iTotalConn = NULL; 128.,代码结构存在什么问题? 代码哪些可以优化?,Overlapped I/O Alertable I/O-Introduction,Instead of using event object notification, make the OS calls one

19、of your functions when I/O operations completeCompletion routines Functions that will be called when I/O complete Specified in the last parameter of WSASend() / WSASendTo() / WSARecv() / WSARecvFrom(),int i = WSARecvFrom(., lpOverlapped, lpCompletionRoutine);,Overlapped I/O Alertable I/O,Move Data P

20、rocessing to the Completion Routine,Overlapped I/O Alertable I/O -Completion Routines,cbTransferred Number of bytes transferred Equals to zero when connection is closed lpOverlapped hEvent can be freely used by your code, just like the LPVOID parameter in thread procedure You have to manage the buff

21、er usage yourself! For example, you issued 10 WSARecv() with 10 buffers The data will be filled in the buffers according to the calling order Reissue WSARecv() on processed buffers,void CALLBACK CompletionRoutine(IN DWORD dwError, /* the error code */IN DWORD cbTransferred, /* in bytes */IN LPWSAOVE

22、RLAPPED lpOverlapped, /* the structure of this I/O */IN DWORD dwFlags );,实例,int main(int argc, char* argv) WSADATA wsaData; SOCKET sListen; SOCKADDR_IN local, client; DWORD dwThreadId; sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); bind(sListen, (sockaddr*) ,DWORD WINAPI WorkerThread(LPVOID lp

23、Param) LPPER_IO_OPERATION_DATA lpPerIOData = NULL; while (TRUE) if (g_bNewConnectionArrived) / Launch an asynchronous operation for new arrived connection lpPerIOData = (LPPER_IO_OPERATION_DATA)HeapAlloc(); lpPerIOData-Buffer.len = MSGSIZE; lpPerIOData-Buffer.buf = lpPerIOData-szMessage; lpPerIOData

24、-sClient = g_sNewClientConnection; WSARecv( lpPerIOData-sClient, ,void CALLBACK CompletionRoutine(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags) LPPER_IO_OPERATION_DATA lpPerIOData = (LPPER_IO_OPERATION_DATA)lpOverlapped; if (dwError != 0 | cbTransferred = 0) / Conn

25、ection was closed by client closesocket(lpPerIOData-sClient); HeapFree(GetProcessHeap(), 0, lpPerIOData); else lpPerIOData-szMessagecbTransferred = 0; send(lpPerIOData-sClient, lpPerIOData-szMessage, cbTransferred, 0); / Launch another asynchronous operation memset( ,完成例程小结,用完成例程来实现重叠I/O比用事件通知简单得多。

26、调用SleepEx使线程处于一种可警告的等待状态,以使得I/O完成后 CompletionROUTINE可以被内核调用。如果辅助线程不调用SleepEx,则内核在完成一次I/O操作后,无法调用完成例程(因为完成例程的运行应该和当初激活WSARecv异步操作的代码在同一个线程之内) 在调用WSARecv时,参数lpOverlapped实际上指向一个比它大得多的结构 。这样,在完成例程中通过参数lpOverlapped拿到的不仅仅是WSAOVERLAPPED结构,还有后边尾随的包含客户端套接字和接收数据缓冲区等重要信息。这样的C语言技巧在我后面介绍完成端口的时候还会使用到。,还有什么模型?,IOCP模型 (对应书上第4章) 微软信箱似乎很完美,老陈也很满意。但是在一些大公司情况却完全不同!这些大公司有数以万计的信箱,每秒钟都有数以百计的信件需要处理,以至于微软信箱经常因超负荷运转而崩溃!需要重新启动!微软不得不使出杀手锏 微软给每个大公司派了一名名叫“Completion Port“的超级机器人,让这个机器人去处理那些信件!,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 企业管理 > 管理学资料

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报