1

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.

2
  • I think the standard library streams are too abstract for what you need, given that fast asynchronous IO mechanisms tend to be quite low level platform specific. I'm reasonably certain you're out of luck in this specific instance. If boost doesn't provide some sort of async stream, you'll have to hunt for another 3rd party library for that purpose.
    – Rook
    Nov 9, 2012 at 12:04
  • 2
    boost::asio is not a general purpose asynchronous I/O library, it is aimed squarely on long-latency streams that non-trivially support select or similar system calls. For asynchronous I/O with disk files one needs a totally different API. Nov 9, 2012 at 13:01

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.