我想异步写入文件。我有一个带有函数的类,该函数接受 vector 和文件名,并将其发送到文件。这个函数可以从类外被调用几千次。
我想执行写异步的原因是......调用者可以只请求写,然后不必担心或等待写完成。
我没有使用套接字、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
还有更多。
有人可以推荐一个文件输入/输出的例子吗?
我问的有道理吗?
最佳答案
我认为你想做的事情非常好,假设你的 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确保不处理对特定文件的调用
平行。
关于c++ - boost asio 以写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16660359/