Boost asio for writing to files

I would like to write files asynchronously. I have a class with a function that takes a vector and a file name and sends it to a file. This function can be called several thousand times, outside the class.

The reason I want to record async is because ... caller can just request a recording, and then don't worry about it or wait for the recording to complete.

I do not use sockets, tcp ...

I look in boost :: asio trying to find examples - all I can find are examples that use the network: http://liveworkspace.org/code/3R3RUd%240

Serialize and send data structure using Boost?

boost :: asio async_read ensure that all bytes are read

And further.

Can someone suggest an example for an i / o file?

Am I asking to make sense?

+4
source share
1 answer

I think what you want to do is fine, assuming your I / O operation is complex enough to handle the overhead of implementing async. My simple suggestion would look like this (copied from an old 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(); } } 

This suggests that you can use C++11 threads. You should also be aware that this does not guarantee that only one stream writes to a specific file. Therefore, you may need to use strands to ensure that calls to a specific file are not processed in parallel to each other.

+6
source

Source: https://habr.com/ru/post/1481854/


All Articles