多线程版本的归并排序
这里的TR和TR2都无需加锁,因为每个Msort处理的数据段都是不一样的。
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void merge(vector<int> TR2, vector<int>& TR, int left, int mid, int right)
{
int i = left, j = mid + 1, a = left;
for(; i <= mid && j <= right; )
{
if(TR2[i] <= TR2[j]) TR[a++] = TR2[i++];
else TR[a++] = TR2[j++];
}
while(i <= mid) TR[a++] = TR2[i++];
while(j <= right) TR[a++] = TR2[j++];
return;
}
void Msort(vector<int> SR, vector<int>& TR, int left, int right)
{
if (left == right)
{
TR[left] = SR[left];
return;
}
vector<int> TR2(SR.size(), 0);
int mid = (left + right) >> 1;
thread one(Msort, SR, std::ref(TR2), left, mid);
thread two(Msort, SR, std::ref(TR2), mid + 1, right);
one.join();
two.join();
merge(TR2, TR, left, mid, right);
}
int main(){
vector<int> test = {2,3,1,6,8,10,20,4,7};
Msort(test, test, 0, static_cast<int>(test.size()) - 1);
for(int i = 0; i < test.size(); i++)
cout << test[i] << endl;
return 0;
}