petersohn
petersohn

Reputation: 11730

Is there a way to use std::iostream objects with boost::asio?

I have a std::iostream object (for example fstream), and I want to use it for asynchronous operations with boost::asio. Is that possible? I know that asio doesn't support file operations, but sometimes it is useful to handle file IO asynchronously. I can use platform-specific native file descriptors and then use them with asio, but I think that using standard C++ streams would be more elegant in C++, and also more portable.

Upvotes: 1

Views: 875

Answers (1)

Tanner Sansbury
Tanner Sansbury

Reputation: 51931

While Boost.Asio does not support file operations, it does provide the toolset for an application to perform file operations in an asynchronous manner. A common approach to accomplishing this is to create a thread pool with Boost.Asio. An application would post the file operation into the thread pool, returning instantly. The thread pool would then execute the operation synchronously, and invoke or post the completion handler when finished.

There are a few points to consider:

  • Allow the application to hint at the concurrency level of the thread pool. This will allow the thread pool to allocate enough threads to fit the application's anticipated need.
  • The thread in which the completion handler will be invoked. For instance, it could be execute in the same thread in which the synchronous operation was executed, or be posted into a different io_service that is provided to the pool when the file operation was posted.
  • The synchronous or asynchronous behavior of the completion handler. For example, if the completion handler is the result of strand::wrap, then it will be invoked asynchronous to the worker thread. As such, the completion handler's arguments must remain valid until the handler is called. This can often be solved by allowing the arguments to be passed-by-value or moved.

Finally, libuv is a C libraries that provides synchronous and asynchrnous file operations. It may be able to serve as a worthwhile underlying implementation or reference material.

Upvotes: 2

Related Questions