Loading... # 重叠IO ``` #include <iostream> #include <Windows.h> #include <tchar.h> int main() { //1 创建文件,得到句柄 HANDLE hFile = CreateFile( _T("D:\\test\\halou.txt"), GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED,//文件是以重叠IO的方式打开的 NULL ); //2 读取数据 char buf1[100] = { 0 }; char buf2[100] = { 0 }; DWORD dwSize = 0; OVERLAPPED oa1 = { 0 }; oa1.hEvent = CreateEvent( NULL, //安全属性 FALSE,//TRUE:手工重置 FALSE:自动重置 FALSE, //TRUE:初始为激发态, FALSE:初始就是非激发态 NULL ); OVERLAPPED oa2 = { 0 }; oa2.hEvent = CreateEvent( NULL, //安全属性 FALSE,//TRUE:手工重置 FALSE:自动重置 FALSE, //TRUE:初始为激发态, FALSE:初始就是非激发态 NULL ); ReadFile( //当读取操作完成的时候,会给oa1中事件,设置为激发态,从而让等待它的地方得到通知 hFile, buf1, 100, &dwSize, &oa1 ); ReadFile(//当读取操作完成的时候,会给oa2中事件,设置为激发态,从而让等待它的地方得到通知 hFile, buf2, 100, &dwSize, &oa2 ); //很多后面的代码.... WaitForSingleObject(hFile, -1); return 0; } ``` # 异步调用 ``` #include <iostream> #include <Windows.h> #include <tchar.h> typedef struct _MYOVERLAPPED { OVERLAPPED oa; char* pBuffer; }MYOVERLAPPED, *PMYOVERLAPPED; VOID WINAPI ReadProc( _In_ DWORD dwErrorCode, _In_ DWORD dwNumberOfBytesTransfered, _Inout_ LPOVERLAPPED lpOverlapped ) { PMYOVERLAPPED overlapped = (PMYOVERLAPPED)lpOverlapped; printf("%s", overlapped->pBuffer); } int main() { //1 创建文件,得到句柄 HANDLE hFile = CreateFile( _T("D:\\test\\halou.txt"), GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED,//文件是以重叠IO的方式打开的 NULL ); //2. 读取数据 PMYOVERLAPPED pOverLapped = new MYOVERLAPPED{0}; pOverLapped->pBuffer = new char[100]{ 0 }; OVERLAPPED oa1 = { 0 }; ReadFileEx( hFile, pOverLapped->pBuffer, 100, (LPOVERLAPPED)pOverLapped, ReadProc ); //3. 什么时候会调用回调函数,两个要求 //3.1 必须IO操作完成了 //3.2 必须当前线程处于空闲状态(可警醒的状态) SleepEx( 0, //其实不想睡 TRUE //处于可警醒 ); return 0; } ``` 最后修改:2021 年 02 月 28 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏