需要有关使用 boost::asio 和 boost::iostreams 进行异步非阻塞文件加载的帮助(或不同的东西?)
我正在用 C++ 编码,并且正在尝试异步加载图像文件。经过一些研究,我发现一些提到使用 boost::asio 和 boost::iostreams 来做到这一点。然而,boost::asio 的文档和示例主要与套接字相关,所以它对我没有多大帮助。
这是我需要的:
- 异步加载文件并在加载完成后执行回调函数。(在我的例子中,回调函数使用 v8 javascript 引擎执行 javascript 函数对象)
- 回调函数必须在与主要功能。 (因为v8不是线程安全的。)
- 需要在linux和windows上工作。 (单独的实现是可以的)
所以,像这样的事情真的很好:
async_read("test.jpg", &the_callback_function);
该函数不应该阻塞,并且在文件加载完成后,它应该运行“the_callback_function”。
编辑:正如 joshperry 指出的那样, boost::asio 可能无法分派回主线程。所以,我想我不必仅限于 boost::asio 和 boost:iostreams。任何可以帮助满足此要求的 c/c++ 库都应该没问题。谢谢!
I'm coding in c++, and I'm trying to load an image file asynchronously. After some research, I found some mentions about using boost::asio and boost::iostreams to do it. However, the documentation and example for boost::asio is mostly socket related, so it doesn't help me much.
Here is what I need:
- Load a file asynchronously and upon load completion, executes a callback function.(In my case, the callback function executes a javascript function object using v8 javascript engine)
- The callback function must be executed within the same thread as the main function. ( Because v8 is not thread safe.)
- Need to work on linux and windows. (separate implementations are ok)
So, something like this would be really nice:
async_read("test.jpg", &the_callback_function);
The function should not block, and upon file load completion, it should run 'the_callback_function'.
Edit: as joshperry pointed out, boost::asio might not be able to dispatch back to the main thread. So, I guess I don't have to limit to only boost::asio and boost:iostreams. Any c/c++ library that can help with this requirement should be fine. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用更多的脚手架来完成您想要的操作,但是为了在主线程上执行回调,主线程必须等待表明回调已准备就绪的信号。这是一种方法。我假设您的主线程已经具有某种形式的执行循环。
使用 STL 和同步对象(例如 Boost.Thread 提供的对象)可移植地构建这样一个队列并不困难。将其构建为无争用的高吞吐量是另一回事,但听起来您并不需要这种扩展。即使其他库会为您完成所有这些工作,对于任何进行多线程编程的人来说,自己构建这样的东西也是一项很好的练习,特别是当所涉及的一个或多个组件不可重入时。
You can do what you want with a little more scaffolding, but in order for the callback to be executed on your main thread, the main thread must be waiting on something which signals that the callback is ready. Here's one way to do it. I'm assuming that your main thread already has some form of execution loop.
It's not hard to build such a queue portably using STL and synchronization objects (such as those provided by Boost.Thread). Building it to scale to high-throughput without contention is another matter, but it doesn't sound like you need that kind of scaling. Even if other libraries will do all this for you, building something like this yourself is a great exercise for anyone doing multithreaded programming, particular if one or more of the components involved are not re-entrant.