当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
怀念故乡的面条
C# | 使用Json序列化对象时忽略只读的属性
This article takes you to understand the past and present of Mimir, Grafana's latest open source project
Dry goods!How to Construct SRv6-TE Performance Test Environment Using Instrumentation
Pyspark Machine Learning: Vectors and Common Operations
(2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
Logitech Mouse Experience Record
High Numbers | 【Re-integration】Line Area Score 880 Examples
(Codeforce 757)E. Bash Plays with Functions(积性函数)
UE4 制作遇到的问题
随机推荐
Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
typescript27-枚举类型呢
typescript28-枚举类型的值以及数据枚举
Message queue design based on mysql
C# | 使用Json序列化对象时忽略只读的属性
数据比对功能调研总结
typescript24 - type inference
Article summary: the basic model of VPN and business types
Swastika line-by-line parsing and realization of the Transformer, and German translation practice (2)
高数 | 【重积分】线面积分880例题
Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]
今日睡眠质量记录68分
MySQL Practice Summary -
"ArchSummit: The cry of the times, technical people can hear"
万字逐行解析与实现Transformer,并进行德译英实战(三)
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
基于Arduino制作非接触式测温仪
万字逐行解析与实现Transformer,并进行德译英实战(一)
初识shell脚本
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”