linux

Linux环境下C++如何进行异步I/O操作

小樊
42
2025-10-23 09:46:44
栏目: 编程语言

在Linux环境下,C++可以通过多种方式实现异步I/O操作。以下是一些常用的方法:

1. 使用libaio

libaio是Linux提供的异步I/O库,可以用于执行异步读写操作。

示例代码:

#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <libaio.h>

void async_read(int fd, off_t offset, size_t length) {
    io_context_t ctx = 0;
    io_setup(1, &ctx);

    struct iocb cb;
    io_prep_pread(&cb, fd, nullptr, length, offset);
    cb.data = (void*)1;

    if (io_submit(ctx, 1, &cb) != 1) {
        std::cerr << "io_submit failed" << std::endl;
        return;
    }

    struct io_event events[1];
    while (io_getevents(ctx, 1, 1, events, nullptr) > 0) {
        if (events[0].res < 0) {
            std::cerr << "io_getevents failed" << std::endl;
            break;
        }
        std::cout << "Read " << events[0].res << " bytes" << std::endl;
    }

    io_destroy(ctx);
}

int main() {
    int fd = open("test.txt", O_RDONLY);
    if (fd < 0) {
        std::cerr << "Failed to open file" << std::endl;
        return 1;
    }

    async_read(fd, 0, 1024);

    close(fd);
    return 0;
}

2. 使用epoll

epoll是Linux提供的I/O事件通知机制,可以用于异步I/O操作。

示例代码:

#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/epoll.h>

void async_read(int fd) {
    int epoll_fd = epoll_create1(0);
    if (epoll_fd < 0) {
        std::cerr << "epoll_create1 failed" << std::endl;
        return;
    }

    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = fd;

    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0) {
        std::cerr << "epoll_ctl failed" << std::endl;
        close(epoll_fd);
        return;
    }

    char buffer[1024];
    while (true) {
        int num_bytes = read(fd, buffer, sizeof(buffer));
        if (num_bytes < 0) {
            std::cerr << "read failed" << std::endl;
            break;
        }
        if (num_bytes == 0) {
            std::cout << "EOF reached" << std::endl;
            break;
        }
        std::cout << "Read " << num_bytes << " bytes" << std::endl;
    }

    close(epoll_fd);
}

int main() {
    int fd = open("test.txt", O_RDONLY);
    if (fd < 0) {
        std::cerr << "Failed to open file" << std::endl;
        return 1;
    }

    async_read(fd);

    close(fd);
    return 0;
}

3. 使用std::futurestd::async

C++11引入了std::futurestd::async,可以用于实现异步操作。

示例代码:

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

std::string async_read(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("Failed to open file");
    }

    std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    return content;
}

int main() {
    auto future = std::async(std::launch::async, async_read, "test.txt");

    // Do other work here

    try {
        std::string content = future.get();
        std::cout << "Read " << content.size() << " bytes" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}

4. 使用asio

asio是一个跨平台的C++库,用于网络和低层I/O编程,支持异步操作。

示例代码:

#include <iostream>
#include <fstream>
#include <asio.hpp>

using asio::ip::tcp;

void async_read(asio::io_context& io_context, const std::string& filename) {
    std::ifstream file(filename, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Failed to open file" << std::endl;
        return;
    }

    asio::streambuf buffer;
    asio::async_read(file, buffer,
        [&buffer](std::error_code ec, std::size_t bytes_transferred) {
            if (!ec) {
                std::cout << "Read " << bytes_transferred << " bytes" << std::endl;
                std::istream is(&buffer);
                std::string content((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());
                std::cout << content << std::endl;
            } else {
                std::cerr << "Error: " << ec.message() << std::endl;
            }
        });

    io_context.run();
}

int main() {
    asio::io_context io_context;
    async_read(io_context, "test.txt");
    return 0;
}

这些方法各有优缺点,选择哪种方法取决于具体的应用场景和需求。libaioepoll更适合底层系统编程,而std::futurestd::async以及asio则更适合应用层编程。

0
看了该问题的人还看了