简体   繁体   English

有没有办法在 boost::asio 中使用 std::iostream 对象?

[英]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 .我有一个std::iostream对象(例如fstream ),我想将它用于boost::asio异步操作。 Is that possible?那可能吗? I know that asio doesn't support file operations, but sometimes it is useful to handle file IO asynchronously.我知道 asio 不支持文件操作,但有时异步处理文件 IO 很有用。 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.我可以使用特定于平台的本机文件描述符,然后将它们与 asio 一起使用,但我认为在 C++ 中使用标准 C++ 流会更优雅,也更可移植。

While Boost.Asio does not support file operations, it does provide the toolset for an application to perform file operations in an asynchronous manner.虽然 Boost.Asio 不支持文件操作,但它确实为应用程序以异步方式执行文件操作提供了工具集。 A common approach to accomplishing this is to create a thread pool with Boost.Asio.实现这一点的常用方法是使用 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.例如,它可以在执行同步操作的同一线程中执行,或者发布到发布文件操作时提供给池的不同io_service中。
  • 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.例如,如果完成处理程序是strand::wrap的结果,那么它将与工作线程异步调用。 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.最后, libuv是一个提供同步和异步文件操作的 C 库。 It may be able to serve as a worthwhile underlying implementation or reference material.它可以作为有价值的底层实现或参考材料。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM