Add MT merger

This commit is contained in:
Robin Dietzel 2023-11-03 11:32:02 +01:00
parent cd742751ed
commit c8a3a6d4e3
3 changed files with 51 additions and 2 deletions

View File

@ -19,7 +19,8 @@ add_custom_target(task1_7_dataset
${CMAKE_CURRENT_BINARY_DIR}/dataset.dat)
add_executable(task1_7 main.cpp
mergesort.h)
mergesort.h
mergesort_mt.h)
target_link_libraries(task1_7
fmt::fmt

View File

@ -305,7 +305,7 @@ namespace algo {
while (l < left.end() && r < right.end()) {
if (cmp(*l, *r)) {
output.insert(o, *l);
outpbufut.insert(o, *l);
l++;
} else {
output.insert(o, *r);

48
task1/mergesort_mt.h Normal file
View File

@ -0,0 +1,48 @@
#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());
}
}
};