[英]Launching Multiple Threads in a single call C++ 11
据我了解,在C ++ 11中创建多个线程的典型方法是:
int num_threads = 10;
std::thread threads[num_threads];
for(int i = 0; i < num_threads; ++i)
{
threads[i] = std::thread(doSomething);
}
// Call join if you need all threads completion
for(int i = 0; i < num_threads; ++i)
{
threads[i].join();
}
是否可以一次性启动线程,而不是使用循环顺序启动每个线程。 我知道在CUDA中,线程是同时启动的,不需要单独启动每个线程。 想知道在C ++ 11中是否有可能实现类似的目标
是的,您可以生成一个将在一个语句中启动n
线程(逻辑上)的操作。
template<class F>
std::future<void> launch_tasks( F&& f, size_t n ) {
if (n==0) { // ready future case, launch 0 threads:
std::promise<void> p;
p.set_value();
return p.get_future();
}
std::vector<std::future<void>> results;
results.reserve(n-1);
for (size_t i = 0; i < n-1; ++i) {
results.push_back(
std::async(
std::launch::async,
f, i
)
);
}
// last thread waits on the previous threads before finishing:
return std::async(
std::launch::async,
[results=std::move(results),f=std::forward<F>(f)]{
f(results.size());
for (auto&& others:results)
others.wait();
}
};
}
只需调用launch_tasks( [](size_t i) { /* code */ }, n )
将启动n
任务,每个任务都有一个索引。 返回的future将阻止所有已完成的任务,而无需为该任务使用额外的线程。
最后一个lambda使用C ++ 14功能(通用捕获)。 您可以这样编写一个函数对象:
template<class F>
struct work_then_wait {
F f;
std::vector<std::future<void>> futures;
void operator()()const{
f(futures.size());
for (auto&& f:results)
f.wait();
}
};
然后
return work_then_wait<typename std::decay<F>::type>{
std::forward<F>(f),
std::move(results)
};
而不是lambda,它是等效的,但用C ++ 11编写。
一个更简单的版本在所有等待所有期货的任务上使用std::async( std::launch::deferred
,但是这使wait_until
和其他定时等待返回的future
无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.