我正在尝试使用 boost::threadpool
(不是 boost
的官方部分,link)并行化我程序的某个方面。但是,我发现我的程序停顿了,经过检查,htop
显示有两个非事件线程(我怀疑在我的线程池中)和一个以 100% 速度运行的线程(我怀疑我的主执行线程) .
相关代码如下:
namespace rt {
class Renderer
{
public:
Renderer(int threads) : tp(threads) {}
void render(const Scene&, const Camera&, Image&) const;
private:
mutable boost::threadpool::pool tp;
//int tp;
static void render(const Scene&, const Camera&, Image&, int, int);
static Color trace_ray(const Ray&, const Scene&, int depth = 0);
};
} // namespace rt
void
Renderer::render(const Scene& scene, const Camera& cam, Image& image) const
{
for (int y = 0; y < image.get_height(); ++y)
for (int x = 0; x < image.get_width(); ++x)
tp.schedule(boost::bind(&Renderer::render, scene, cam, image, x, y));
tp.wait();
}
void
Renderer::render(const Scene& scene, const Camera& cam, Image& image, int x, int y)
{
Color c = trace_ray(cam.spawn_ray(x + .25f, y + .25f), scene)
+ trace_ray(cam.spawn_ray(x + .75f, y + .25f), scene)
+ trace_ray(cam.spawn_ray(x + .25f, y + .75f), scene)
+ trace_ray(cam.spawn_ray(x + .75f, y + .75f), scene);
image.set_pixel(x, y, c / 4.0f);
}
我怀疑问题出在我的 boost::bind
构造上的原因是,当我创建一个 void foobar() {}
函数并将其传递给 boost::threadpool::pool::schedule
,程序不会进入无限循环。我在这里做错了什么?
最佳答案
boost::bind
的参数 will be copied .
The arguments that bind takes are copied and held internally by the returned function object. For example, in the following code:
int i = 5;
bind(f, i, _1); a copy of the value of i is stored into the function object. boost::ref and boost::cref can be used to make the function object store a reference to an object, rather than a copy.
在你的情况下:
tp.schedule(boost::bind(&Renderer::render, scene, cam, image, x, y));
会将 cam
、image
、x
和 y
的拷贝发送到 Rendered::渲染
。这是你想要的吗?
关于c++ - 将 boost::threadpool 与 boost::bind 一起使用会使我的程序陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892994/