当前位置:网站首页>Asynchronous reading and writing of files
Asynchronous reading and writing of files
2022-08-01 04:50:00 【Fang Chi Anxia】
目录
Files are read and written asynchronously
1: Ordinary read and write files and open files are synchronous,比如C的fopen, fclose, fread等;
2: The access speed of disk is much lower than that of memory,所以OSTo wait for the disk device to read and write.
3: 如果采用同步,Then the task will hang,Wait for the disk to read the data,通知OS.
4: 高性能的服务器,提高并发,Reading and writing files will use asynchronous mode.
5: 异步的模式:
1>Issue a request to read the file;
2>Notify the app when you're done,并处理;
win同步读
1: Open a file synchronously:
HANDLE hFile = CreateFile(路径, GENERIC_READ, 0,
NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
GENERIC_READ只读的方式;
2: Read a file synchronously:ReadFile(hFile, buf, max_len,&dwRead,&overlap);
3: 关闭一个文件: CloseHandle(hFile);
Win异步读
1: Open a file asynchronously:
HANDLE hFile = CreateFile(路径, GENERIC_READ, 0,
NULL,OPEN_EXISTING,
FILE_FLAG_OVERLAPPED|FILE_ATTRIBUTE_NORMAL,NULL);
FILE_FLAG_OVERLAPPED: Flag to open the file asynchronously, GENERIC_READ只读的方式;
2: 创建一个OVERLAPPED对象,传递给OS,Carry an event,when reading is complete,触发事件;
OVERLAPPED overlap;
overlap.Offset = 0; //The offset at which to start reading and writing the file,The offset is calculated from the beginning of the file
overlap.OffsetHigh =0; //64The higher of the file offset position of the bit32位
overlap.hEvent = hEvent;
3: 读文件: ReadFile(hFile, buf, max_len,&dwRead,&overlap);
4:Add the event to the wait collection to wait for completion.
WaitForSingleObject/WaitForMultipleObjects,GetLastError获取错误信息
5: 关闭一个文件: CloseHandle(hFile);
同步与异步的区别
1: all have to wait,One is to control in the user plane,One is in kernel control;
2: Synchronization in the kernel etc,灵活度不够, Really can only wait for one,但是简单;
3: The user controls the wait,Multiple processing can be waited at the same time;
4: 异步:可以同时处理多个请求,发出请求后,Wait for all these events,Deal with them as they end,继续等待;
Waiting for multiple handles at the same time
1:
DWORD WaitForMultipleObjects(
DWORD nCount, // Specifies the number of handles in the list 最大值为MAXIMUM_WAIT_OBJECTS
CONST HANDLE *lpHandles, // 句柄数组的指针
BOOL fWaitAll, // 等待的类型,如果为TRUE,Indicates unless the object both emits a signal,否则就一直等待下去;如果FALSE,Indicates that any object emits a signal
DWORD dwMilliseconds // Specifies the number of milliseconds to wait.如设为零,表示立即返回.such as specifying constantsINFINITE,You can wait indefinitely according to the actual situation
);
2: 返回值:
WAIT_TIMEOUT: The object remains in an unsignaled state,But the specified wait timeout time has been exceeded
WAIT_OBJECT_0: All objects emit signals;
WAIT_FAILED: 执行失败,可以通过GetLastError获取错误信息;
nIndex : WAIT_OBJECT_0 + 5, 第5object emits an event;
demo
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Windows.h>
int main(int argc, char** argv)
{
#if 0
//同步
char buf[1024];
DWORD readed = 1024;
int ret;
//HANDLE 句柄: The unique identifier of the current object
HANDLE hfile = INVALID_HANDLE_VALUE; // Open failure or return failure will beINVALID_HANDLE_VALUE
hfile = CreateFile(L"bin//in.txt", GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // OPEN_EXISTING Open an existing file
if (hfile == INVALID_HANDLE_VALUE)
{
printf("open error\n");
goto failed;
}
ret = ReadFile(hfile, buf, 1024, &readed, NULL);
if (ret == 0)
{
goto failed;
}
buf[readed] = 0;
printf("%s\n", buf);
#else
//异步 FILE_FLAG_OVERLAPPED 模式
char buf[1024];
DWORD readed = 1024;
OVERLAPPED overlap;
memset(&overlap, 0, sizeof(overlap));
HANDLE hevent = CreateEvent(NULL, false, false, NULL);
HANDLE hfile = INVALID_HANDLE_VALUE; // Open failure or return failure will beINVALID_HANDLE_VALUE
hfile = CreateFile(L"bin//in.txt", GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_ATTRIBUTE_NORMAL, NULL); // OPEN_EXISTING Open an existing file
if (hfile == INVALID_HANDLE_VALUE)
{
printf("open error\n");
goto failed;
}
//读的时候, 发送请求, 准备一个OVERLAPPED对象
// 传给OS, 等OS读完以后, 会通过OVERLAPPEDSend us an event
overlap.hEvent = hevent;
overlap.Offset = 0; // 从第0个字符开始读起
// 马上返回, IO挂起, 没有读到数据,ERROR_IO_PENDING状态
ReadFile(hfile, buf, 1024, &readed, &overlap);
if (GetLastError() == ERROR_IO_PENDING)
{
WaitForSingleObject(hevent, INFINITE); //一直等待
readed = overlap.InternalHigh; //One byte of data was read;
buf[readed] = 0;
printf("async %s\n", buf);
}
#endif
CloseHandle(hfile);
failed:
return 0;
}
边栏推荐
- What is dynamic programming and what is the knapsack problem
- 万字逐行解析与实现Transformer,并进行德译英实战(一)
- Article summary: the basic model of VPN and business types
- (2022牛客多校四)N-Particle Arts(思维)
- ModuleNotFoundError: No module named ‘tensorflow.keras‘报错信息的解决方法
- 高数 | 【重积分】线面积分880例题
- 25. 这三道常见的面试题,你有被问过吗?
- Pyspark Machine Learning: Vectors and Common Operations
- 风险策略调优中重要的三步分析法
- 律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
猜你喜欢

【愚公系列】2022年07月 Go教学课程 024-函数

MySQL-DML语言-数据库操作语言-insert-update-delete-truncate

微软 Win10 照片磁贴后的又一“刺客”,谷歌 Chrome 浏览器将在新标签页展示用户照片

Logitech Mouse Experience Record

数组问题之《两数之和》以及《三数之和 》

7 行代码搞崩溃 B 站,原因令人唏嘘!

Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers

怀念故乡的面条

(Codeforce 757)E. Bash Plays with Functions(积性函数)

typescript28-枚举类型的值以及数据枚举
随机推荐
"ArchSummit: The cry of the times, technical people can hear"
How to promote new products online?
Flink 1.13 (8) CDC
MySQL-数据定义语言-DDLdatebase define language
Interview Blitz 69: Is TCP Reliable?Why?
typescript26 - literal types
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
Step by step hand tearing carousel Figure 3 (nanny level tutorial)
Pyspark机器学习:向量及其常用操作
【堆】小红的数组
25. 这三道常见的面试题,你有被问过吗?
李迟2022年7月工作生活总结
typescript22-接口继承
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers
PMP 项目质量管理
Typescript20 - interface
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
LeetCode 231. 2 的幂