2013-05-21 91 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

你有沒有把這段代碼放入編譯器? –