并行化的基本规则是将工作分解,处理部分,然后组合部分。
哈希/项目查找是整个 shebang 中最昂贵的部分,因此我们将重点关注并行化。
如果您绝对需要将结果作为哈希表,我有一些坏消息要告诉您:您必须自己编写。话虽如此,让我们开始吧。
首先,让我们串行解决问题。这很简单。下面的函数接受一个向量和一个回调。我们将获取向量,将其转换为unordered_set,并将unordered_set 提供给回调。简单的?是的。
现在,因为我们要在一个线程上执行此操作,所以我们不能立即执行此操作。相反,我们将返回一个不带参数的 lambda。当调用该 lambda 时,它将创建 unordered_set 并将其提供给回调。这样,我们可以将每个 lambda 分配给它自己的线程,每个线程将通过调用 lambda 来运行作业。
template<class Vector, class Callback>
auto lazyGetUnique(Vector& vector, Callback callback) {
using Iterator = decltype(vector.begin());
auto begin = vector.begin();
auto end = vector.end();
using elem_t = typename std::iterator_traits<Iterator>::value_type;
//We capture begin, end, and callback
return [begin, end, callback]() {
callback(std::unordered_set<elem_t>(begin, end));
};
}
现在 - 这个回调应该做什么?答案很简单:回调应该将unordered_set 的内容分配给一个向量。为什么?因为我们要合并结果,合并向量比合并unordered_set 快得多。
让我们编写一个函数来给我们回调:
template<class Vector>
auto assignTo(Vector& v) {
return [&](auto&& contents) {
v.assign(contents.begin(), contents.end());
};
}
假设我们想要获取向量的唯一元素,并将它们分配回该向量。现在做起来真的很简单:
std::vector<int> v = /* stuff */;
auto new_thread = std::thread( lazyGetUnique(v, assignTo(v)) );
在本例中,当new_thread 完成执行时,v 将只包含唯一元素。
让我们看看完成所有事情的完整功能。
template<class Iterator>
auto getUnique(Iterator begin, Iterator end) {
using elem_t = typename std::iterator_traits<Iterator>::value_type;
std::vector<elem_t> blocks[4];
//Split things up into blocks based on the last 4 bits
//Of the number. This allows us to guarantee that no two blocks
//share numbers.
for(; begin != end; ++begin) {
auto val = *begin;
blocks[val & 0x3].push_back(val);
}
//Each thread will run their portion of the problem.
//Once it's found all unique elements, it'll stick the result in the block used as input
auto thread_0 = std::thread( lazyGetUnique(blocks[0], assignTo(blocks[0])) );
auto thread_1 = std::thread( lazyGetUnique(blocks[1], assignTo(blocks[1])) );
auto thread_2 = std::thread( lazyGetUnique(blocks[2], assignTo(blocks[2])) );
//We are thread_3, so we can just invoke it directly
lazyGetUnique(blocks[3], assignTo(blocks[3]))(); //Here, we invoke it immediately
//Join the other threads
thread_0.join();
thread_1.join();
thread_2.join();
std::vector<elem_t> result;
result.reserve(blocks[0].size() + blocks[1].size() + blocks[2].size() + blocks[3].size());
for(int i = 0; i < 4; ++i) {
result.insert(result.end(), blocks[i].begin(), blocks[i].end());
}
return result;
}
这个函数把东西分成 4 个块,每个块都是不相交的。它在 4 个块中的每个块中找到唯一元素,然后组合结果。输出是一个向量。