当前位置:网站首页>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;
}
边栏推荐
- The Principle Of Percona Toolkit Nibble Algorithm
- typescript23-tuple
- Excel record of integer programming optimization model to solve the problem
- typescript27 - what about enumeration types
- 律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
- Li Chi's work and life summary in July 2022
- C# | 使用Json序列化对象时忽略只读的属性
- Swastika line-by-line parsing and realization of the Transformer, and German translation practice (2)
- typescript25 - type assertion
- 微软 Win10 照片磁贴后的又一“刺客”,谷歌 Chrome 浏览器将在新标签页展示用户照片
猜你喜欢

typescript27 - what about enumeration types

PAT乙级 1002 写出这个数

FFmpeg 搭建本地屏幕录制环境

High Numbers | 【Re-integration】Line Area Score 880 Examples

【愚公系列】2022年07月 Go教学课程 023-Go容器之列表

Typescript20 - interface

Message queue MySQL table for storing message data

Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink

律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性

怀念故乡的月亮
随机推荐
【云原生之kubernetes实战】kubernetes集群的检测工具——popeye
Excel record of integer programming optimization model to solve the problem
LeetCode 231. 2 的幂
What is dynamic programming and what is the knapsack problem
【无标题】
typescript20-接口
挑战52天背完小猪佩奇(第01天)
TIM登陆时提示00001(TIM00001)
typescript24 - type inference
雪糕和轮胎
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
UE4 制作遇到的问题
typescript22-接口继承
Flutter Tutorial 01 Configure the environment and run the demo program (tutorial includes source code)
This article takes you to understand the past and present of Mimir, Grafana's latest open source project
【愚公系列】2022年07月 Go教学课程 025-递归函数
「以云为核,无感极速」顶象第五代验证码
时时刻刻保持敬畏之心
FFmpeg 搭建本地屏幕录制环境
The kernel's handling of the device tree