aca-tasks/task1/mergesort_mt.h

48 lines
1.0 KiB
C
Raw Normal View History

2023-11-03 10:32:02 +00:00
#include <vector>
#include <span>
#include <thread>
#include <mutex>
template<typename T, typename C>
class MergeSorterMT {
C comp;
std::recursive_mutex mut;
auto merge(std::span<T> &output, std::span<T> left, std::span<T> right) -> void {
std::vector<T> buf;
buf.reserver(left.size() + right.size());
auto l = left.begin();
auto r = right.begin();
auto o = buf.begin();
hile (l < left.end() && r < right.end()) {
if (cmp(*l, *r)) {
buf.insert(o, *l);
l++;
} else {
buf.insert(o, *r);
r++;
}
o++;
}
while (l < left.end()) {
buf.insert(o, *l);
o++;
l++;
}
while (r < right.end()) {
buf.insert(o, *r);
o++;
r++;
}
{
std::lock_guard<std::recursive_mutex> lock(mut);
std::move(buf.begin(), buf.end(), output.begin());
}
}
};