C++多线程:如何为许多“作业”重用线程?
我正在学习 C++ 并且正在制作一个实时光线追踪器。首先我使用 std::thread 来传播工作,但结果证明每帧启动 32 个线程比需要完成的实际工作慢得多。
然后我发现 C++ 也使用线程池通过 std::async() 来处理这个问题:
void trace()
{
constexpr unsigned int thread_count = 32;
std::future<void> tasks[thread_count];
for (auto i = 0u; i < thread_count; i++)
tasks[i] = std::async(std::launch::async, raytrace_task(sample_count, world_), 10, 10);
for (auto i = 0u; i < thread_count; i++)
tasks[i].wait();
}
并且 raytrace_task 为空:
struct raytrace_task
{
// simple ctor omitted for brevity
void operator()(int y_offset, int y_count)
{
}
}
但这与制作自己的线程一样慢。每次调用 trace() 大约需要 30 毫秒!谁能告诉我我做错了什么或如何重用线程?又名:在整个时间内将许多数据处理作业发布到单个重用线程。
谢谢你