您可以使用std::future
和std::async
輕鬆並行計算。
未測試(僞)代碼:
// You need to keep track of all futures you spawn.
std::vector<std::future<bool>> futs;
// Spawn a future for every "block" that you want to check.
futs.emplace_back(std::async(std::launch::async,
[&]{ return check_condition_range(listNumbers, 0, 10000); }));
futs.emplace_back(std::async(std::launch::async,
[&]{ return check_condition_range(listNumbers, 10000, 20000); }));
// (Ideally you would divide your range evenly depending on the number of threads you
// can spawn, and generate the futures in a loop.)
// ...
// "Accumulate" the results of every future.
// This blocks until all futures are done.
bool satisfied = true;
for(auto& f : futs)
{
if(!f.get())
{
satisfied = false;
}
}
Here's a simple example on wandbox。
如果你有機會訪問C++ 17,你可以簡單地使用:
std::all_of(std::execution::par,
std::begin(listNumbers), std::end(listNumbers),
check_if_condition_satisfied);
對不起,我還需要將結果存儲在一個共同的載體。
你的未來型只需更改爲std::future<decltype(listNumbers)::iterator>
,讓每一位將來會返回一個迭代器,而不是一個bool的。
之後,你可以做一些與此類似:
std::vector<decltype(listNumbers)::iterator> result;
for(auto& f : futs) result.emplace_back(f.get());
// use `result`
您是否需要跨平臺解決方案? –
['std :: all_of'](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of)與適當的執行策略。但不幸的是它是C++ 17。 – StoryTeller
聽起來像你真正想要做的不是檢查每一個,但存儲的方式,這意味着你可以更快地減少設置 – UKMonkey