当前位置:网站首页>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;
}
边栏推荐
- API设计笔记:pimpl技巧
- FFmpeg 搭建本地屏幕录制环境
- In the shake database, I want to synchronize the data of the source db0 to the destination db5, how to set the parameters?
- PMP子过程定义总结
- 请问shake数据库中为什么读取100个collection 后,直接就退出了,不继续读了呢?
- 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
- PMP 80个输入输出总结
- 基于STM32设计的UNO卡牌游戏(双人、多人对战)
- 项目风险管理必备内容总结
- 2022-07-31: Given a graph with n points and m directed edges, you can use magic to turn directed edges into undirected edges, such as directed edges from A to B, with a weight of 7.After casting the m
猜你喜欢
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
怀念故乡的月亮
UE4 从鼠标位置射出射线检测
万字逐行解析与实现Transformer,并进行德译英实战(一)
Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers
UE4 模型OnClick事件不生效的两种原因
typescript27-枚举类型呢
6-23漏洞利用-postgresql代码执行利用
初识shell脚本
(2022 Nioke Duo School IV) D-Jobs (Easy Version) (3D prefix or)
随机推荐
MySQL实践总结-
(more than 2022 cattle school four) A - Task Computing + dynamic programming (sort)
typescript24 - type inference
Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]
怀念故乡的月亮
Mysql基础篇(Mysql数据类型)
【愚公系列】2022年07月 Go教学课程 025-递归函数
动态规划 01背包
律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
August 22 Promotion Ambassador Extra Reward Rules
请问shake数据库中想把源的db0的数据同步到目的db5,参数怎么设置呢?
数组问题之《两数之和》以及《三数之和 》
7月编程排行榜来啦!这次有何新变化?
Advice given by experts with four years of development experience in Flutter tutorial
typescript22-接口继承
【云原生之kubernetes实战】kubernetes集群的检测工具——popeye
Passive anti-islanding-UVP/OVP and UFP/OFP passive anti-islanding model simulation based on simulink
认真对待每一个时刻
Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”