[英]Launching Multiple Threads in a single call C++ 11
The typical way to create multiple threads in C++ 11 as I understand is: 据我了解,在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();
}
Is it possible to launch the threads in one shot, instead of using a loop to start each thread sequentially. 是否可以一次性启动线程,而不是使用循环顺序启动每个线程。 I know in CUDA, threads are launched simultaneously and there is no need to start each one individually.
我知道在CUDA中,线程是同时启动的,不需要单独启动每个线程。 Wondering if something similar is possible in C++ 11.
想知道在C ++ 11中是否有可能实现类似的目标
Yes, you can generate an operation that will launch n
threads (well, logically) in one statement. 是的,您可以生成一个将在一个语句中启动
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();
}
};
}
simply call launch_tasks( [](size_t i) { /* code */ }, n )
will launch n
tasks, each given an index. 只需调用
launch_tasks( [](size_t i) { /* code */ }, n )
将启动n
任务,每个任务都有一个索引。 The future that is returned will block on all of the tasks being completed, without using an extra thread for that task. 返回的future将阻止所有已完成的任务,而无需为该任务使用额外的线程。
This is using a C++14 feature (generalized capture) for the last lambda. 最后一个lambda使用C ++ 14功能(通用捕获)。 You can write a function object like this:
您可以这样编写一个函数对象:
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();
}
};
then 然后
return work_then_wait<typename std::decay<F>::type>{
std::forward<F>(f),
std::move(results)
};
instead of the lambda and it is equivalent, but written in C++11. 而不是lambda,它是等效的,但用C ++ 11编写。
A simpler version uses std::async( std::launch::deferred
on a task that waits on all the futures, but that makes wait_until
and other timed waits on the returned future
useless. 一个更简单的版本在所有等待所有期货的任务上使用
std::async( std::launch::deferred
,但是这使wait_until
和其他定时等待返回的future
无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.