c++ - 将 boost::threadpool 与 boost::bind 一起使用会使我的程序陷入无限循环

标签 c++ boost bind threadpool raytracing

我正在尝试使用 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));

会将 camimagexy 的拷贝发送到 Rendered::渲染。这是你想要的吗?

关于c++ - 将 boost::threadpool 与 boost::bind 一起使用会使我的程序陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892994/

相关文章:

c++ - 结构可以在方法体内声明,但前提是它不包含成员字段初始值设定项。编译器错误与否?

c++ - 为什么我们不能在没有基类指针或引用的情况下在 C++ 中实现多态性?

c++ - Qt:如何通过系统调用捕获错误?

具有单子(monad)绑定(bind)的 F# 尾递归

c++ - LeetCode问题:改进执行时间而不使用哈希吗?

c++ - 在Boost::Hana中使用BOOST_HANA_DEFINE_STRUCT定义具有40个以上字段的结构

c++ - 将 GUI 添加到非托管/boost C++ 应用程序

c++ - 我怎么知道boost线程是否完成?

Javascript/Jquery 问题 - playStateChange,Mediaplayer 对象 IE9 ... 试图让 Jquery bind() 处理此事件 ...继续阅读

JavaScript:将对象绑定(bind)到 DOM 元素