2013-05-21 95 views
4

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

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

我不使用插座,TCP ...

我期待到的boost :: ASIO,试图找到例子 - 所有我能找到的是使用网络的例子: http://liveworkspace.org/code/3R3RUd%240

Serialize and send a data structure using Boost?

boost::asio async_read guarantee all bytes are read

还有更多。

有人可以请建议一个文件I/O的例子吗?

我问的是什么意思?

回答

6

我认为你想要做的事情非常好,假设你的IO操作足够复杂,以便降低异步实现的开销。我简单的建议是这样的(从旧question复制):

#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以确保并行处理 并未调用特定文件。

+0

谢谢。我正在使用VS2010 ...如果我理解正确,无论是编写同步还是异步,io_operation都是一样的?只有来电者决定如何使用它?此外,如果多个线程可以写入相同的文件...我必须使用某种锁?但是,如果每个线程都使用不同的文件路径调用函数 - 多线程仍可能写入同一个文件吗? – Thalia

+0

@Thalia:是的,操作与没有异步操作时使用的操作相同。如果每个线程都使用不同的文件路径调用该函数,那么您将不会收到我假设的任何错误。确保你必须使用某种锁。链接我在我的帖子是通常的方式来做这个提升asio(看看参考和例子)。但是,如果您愿意,也可以在'io_operation'函数中使用'std :: mutex'。 – Haatschii

+0

你有没有把这段代码放入编译器? –