C++异步IO

异步IO:在异步IO中,首先设置好文件需要读取到哪个变量中,然后文件读取到此变量中的过程都是在内核中操作的,用户程序并不会因为读文件操作而阻塞。当文件读取完毕时,通过特定的方式通知用户程序,比如发送信号SIGIO通知用户程序文件已经读取完毕了。我们可以给信号SIGIO设置回调函数,在回调函数中将获取到的文件信息打印出来看看,注意这里只是将获取的到信息打印出来,并不是从文件中读取信息,读取信息早就在内核中进行过了。你可以这样认为,同步I/O向应用程序通知的是I/O就绪事件,而异步I/O向应用程序通知的是I/O完成事件。

下面是多种一部IO的实现:

C++11

C++11标准中引入了一个新的库,称为<chrono><thread>库,其中包含了一些线程和时间相关的API,可以用于实现异步I/O操作。此外,C++11标准中还引入了<future><async>库,用于实现异步编程模型。虽然C++11中没有像Boost.Asio这样完整的网络编程库,但使用上述库可以实现一些简单的异步I/O操作。

例如,下面是一个使用C++11库实现异步读取文件内容的示例程序:

#include <iostream>
#include <fstream>
#include <future>

int main()
{
    std::cout << "Start" << std::endl;

    // 异步读取文件内容
    std::ifstream file("example.txt");
    auto future = std::async(std::launch::async, [&file](){ // 传入file作为参数
        std::string contents;
        // std::istreambuf_iterator为两个指针,分别指向文件头和文件尾
        contents.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); 
        return contents;
    });
    std::string contents = future.get();
    std::cout << contents << std::endl;

    return 0;
}

aio.h

Linux环境下,aio.h头文件中定义的函数提供了对异步I/O的支持。

// 使用异步io使用文件example.txt的读取
#include <aio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUF_SIZE 100
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main(int argc, char *argv[]) {
  struct aiocb aiocb;
  int fd, ret;
  char buf[BUF_SIZE];

  if (argc != 2) {
    fprintf(stderr, "Usage: %s filename", argv[0]);
    exit(EXIT_FAILURE);
  }

  fd = open(argv[1], O_RDONLY);
  if (fd == -1)
    errExit("open");

  // 初始化aiocb结构体
  memset((void *)&aiocb, 0, sizeof(struct aiocb));
  aiocb.aio_fildes = fd;
  aiocb.aio_offset = 0;
  aiocb.aio_buf = buf;
  aiocb.aio_nbytes = BUF_SIZE;

  // 发送异步读请求
  ret = aio_read(&aiocb);
  if (ret == -1)
    errExit("aio_read");

  // 检查异步读请求是否完成
  while (aio_error(&aiocb) == EINPROGRESS);

  // 读取异步读请求的返回值
  ret = aio_return(&aiocb);
  if (ret == -1)
    errExit("aio_return");

  printf("Read %d bytes", ret);

  if (close(fd) == -1)
    errExit("close");

  exit(EXIT_SUCCESS);
}


posted @   好人~  阅读(678)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示