4

我想异步写入文件。我有一个带有函数的类,该函数接受向量和文件名,并将其发送到文件。这个函数可以从类外调用几千次。

我要执行异步写入的原因是......调用者可以请求写入,然后不必担心它或等待写入完成。

我没有使用套接字,tcp ...

我正在研究 boost:: asio,试图找到示例 - 我能找到的都是使用网络的示例:http: //liveworkspace.org/code/3R3RUd%240

使用Boost序列化和发送数据结构?

boost::asio async_read 保证读取所有字节

和更多。

有人可以推荐一个文件 i/o 的例子吗?

我问的有意义吗?

4

1 回答 1

7

我认为你想要做的非常好,假设你的 IO 操作足够复杂,以证明异步实现的开销。我的简单建议看起来像这样(从一个旧问题复制):

#include <thread>
#include <functional>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

void io_operation(int parameter) {
   //Your stuff
}

int main ( int argc, char* argv[] ) {
    boost::asio::io_service io_service;
    boost::asio::io_service::work work(io_service);

    //Set up a thread pool taking asynchronically care of your orders
    std::vector<std::thread> threadPool;

    for(size_t t = 0; t < std::thread::hardware_concurrency(); t++){
        threadPool.push_back(std::thread(boost::bind(&boost::asio::io_service::run, &io_service)));
    }

    //Post an IO-operation
    io_service.post(std::bind(io_operation, 123));

    //Join all threads at the end
    io_service.stop();
    for(std::thread& t : threadPool) {
        t.join();
    }
}

这假设您可以使用C++11线程。您还应该知道,这并不能确保只有一个线程正在写入特定文件。因此,您可能需要使用strands来确保对特定文件的调用不会并行处理。

于 2013-05-21T00:44:22.783 回答