閱讀Boost.Thread Futures文檔以瞭解使用期貨和async
來實現此目的的想法。它還顯示瞭如何使用thread
對象手動(難度較大)執行此操作。
鑑於這種串行代碼:
double run_sim(Data*);
int main()
{
const unsigned ntasks = 50;
double results[ntasks];
Data data[ntasks];
for (unsigned i=0; i<ntasks; ++i)
results[i] = run_sim(data[i]);
}
一個天真的水貨版本是:
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread/future.hpp>
#include <boost/bind.hpp>
double run_task(Data*);
int main()
{
const unsigned nsim = 50;
Data data[nsim];
boost::future<int> futures[nsim];
for (unsigned i=0; i<nsim; ++i)
futures[i] = boost::async(boost::bind(&run_sim, &data[i]));
double results[nsim];
for (unsigned i=0; i<nsim; ++i)
results[i] = futures[i].get();
}
因爲boost::async
還不支持延遲功能,每一個異步調用將創建一個新的線程,所以這將一次產生50個線程。這可能表現相當糟糕,所以你可以把它分解成更小的塊:
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread/future.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
double run_sim(Data*);
int main()
{
const unsigned nsim = 50;
unsigned nprocs = boost::thread::hardware_concurrency();
if (nprocs == 0)
nprocs = 2; // cannot determine number of cores, let's say 2
Data data[nsim];
boost::future<int> futures[nsim];
double results[nsim];
for (unsigned i=0; i<nsim; ++i)
{
if (((i+1) % nprocs) != 0)
futures[i] = boost::async(boost::bind(&run_sim, &data[i]));
else
results[i] = run_sim(&data[i]);
}
for (unsigned i=0; i<nsim; ++i)
if (((i+1) % nprocs) != 0)
results[i] = futures[i].get();
}
如果hardware_concurrency()
回報4,這將創建三個新主題,然後調用run_sim
同步在main()
線程,然後創建另外三個新主題,然後同步呼叫run_sim
。這將阻止一次創建50個線程,因爲主線程停止執行一些工作,這將允許一些其他線程完成。
上面的代碼需要加速的相當最新版本,它是稍微容易使用標準C++,如果你可以使用C++ 11:
#include <future>
double run_sim(Data*);
int main()
{
const unsigned nsim = 50;
Data data[nsim];
std::future<int> futures[nsim];
double results[nsim];
unsigned nprocs = std::thread::hardware_concurrency();
if (nprocs == 0)
nprocs = 2;
for (unsigned i=0; i<nsim; ++i)
{
if (((i+1) % nprocs) != 0)
futures[i] = std::async(boost::launch::async, &run_sim, &data[i]);
else
results[i] = run_sim(&data[i]);
}
for (unsigned i=0; i<nsim; ++i)
if (((i+1) % nprocs) != 0)
results[i] = futures[i].get();
}
這似乎是['標準:: async'一個很好的工作, ](http://en.cppreference.com/w/cpp/thread/async)和['std :: future'](http://en.cppreference.com/w/cpp/thread/future)(或他們的Boost變體)。 –