非静态成员失败的线程调用函数
Thread calling function with non-static members failing
我创建了一个函数void top()
通过为每个像素发送一条光线来渲染图像。我想把它放在一个线上。我使用了#include <thread>
库,但是当我在main()
方法中声明线程时,它给了我两个错误:错误 C2893 无法专用函数模板"未知类型 std::invoke(_Callable &&,_Types &&...( noexcept((和错误 C2672 'std::invoke':没有匹配的重载函数。我认为这可能是因为void top()
同时调用非静态和静态方法。只是学习线程,所以对问题所在有点困惑。下面的所有函数都在主 cpp 文件中。
void top(int& samples_per_pixel, camera& cam, const color& background, hittable& world, const int& max_depth) {
for (float j = image_height - 1; j >= image_height/2; --j) {
for (int i = 0; i < image_width; ++i) {
color pixel_color(0, 0, 0);
for (int s = 0; s < samples_per_pixel; ++s) {
auto u = (i + random_double()) / (image_width - 1); //Random double is static. From other header file
auto v = (j + random_double()) / (image_height - 1);
ray r = cam.get_ray(u, v); //get_ray() is non-static and in camera class
pixel_color += ray_color(r, background, world, max_depth); //Ray_color defined above top() method in same main cpp file
pixel_color += color(0, 0, 0);
}
auto r = pixel_color.x();
auto g = pixel_color.y();
auto b = pixel_color.z();
auto scale = 1.0 / samples_per_pixel;
r = sqrt(scale * r);
g = sqrt(scale * g);
b = sqrt(scale * b);
int ir = static_cast<int>(256 * clamp(r, 0.0, 0.999));
int ig = static_cast<int>(256 * clamp(g, 0.0, 0.999));
int ib = static_cast<int>(256 * clamp(b, 0.0, 0.999));
pixels[index++] = ir; //pixels defined above top() class
pixels[index++] = ig;
pixels[index++] = ib;
}
}
}
...
int main(){
...
std::thread first(top,samples_per_pixel, cam, background, world, max_depth); //Two errors being called here
first.detach();
}
来自 'std::thread::thread:
线程函数的参数按值移动或复制。如果需要将引用参数传递给线程函数,则必须将其包装(例如,使用
std::ref
或std::cref
(。
因此,只需将您通过引用获取的每个变量包装在其中一个包装器中即可。 如果您不更改线程中的值并相应地调整函数的签名,则更喜欢std::cref
。
与其传递const int&
,不如传递int
。
例:
// new signature:
void top(int samples_per_pixel, camera& cam, const color& background,
hittable& world, int max_depth);
// new starting call:
std::thread first(top, samples_per_pixel, std::ref(cam), std::cref(background),
std::ref(world), max_depth);
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?