基本上,如果合并排序中的列表数等于计算机中的核心数,它将生成一个线程来对每个列表进行排序。它目前可以使用,但是我面临的问题是,与常规的合并排序相比,排序实际上需要更长的时间。它花费了更长的时间,因为它生成了一个线程,而不是同时生成四个线程,而是遍历了整个过程,然后继续调用下一个线程。下面是我编写的代码,它可以工作,但是由于我上面提到的问题,它再次变慢了。如果有人熟悉在排序算法中使用线程,将不胜感激。更进一步,这不是家庭作业,我上课的项目是设计一个普通的合并排序,我
void MergeSortThreading(int low, int high, int* source, int* destination, int count)
{
if (low == high)
return;
int mid = (low + high) / 2;
int start_1 = low, end_1 = mid, start_2 = (mid + 1), end_2 = high, dest = start_1;
if (pow(2, count) == cores())
{
thread* processes = new thread[cores()];
int j = 1;
for (int i = 0; i < cores(); i++)
{
processes[i] = thread(MergeSortThreading, j, (j + (high)), destination, source, 1000);
j += (high - 1);
}
for (int i = 0; i < cores(); i++)
processes[i].join();
}
MergeSortThreading(low, mid, destination, source, ++count);
MergeSortThreading((mid + 1), high, destination, source, 150);
while (start_1 <= end_1 && start_2 <= end_2)
{
if (source[start_1] > source[start_2])
destination[dest++] = source[start_2++];
else
destination[dest++] = source[start_1++];
}
if (start_1 > end_1)
{
for (; start_2 <= end_2; start_2++)
{
destination[dest] = source[start_2];
dest++;
}
}
else
{
for (; start_1 <= end_1; start_1++)
{
destination[dest] = source[start_1];
dest++;
}
}
}
并行化递归的一种非常简单的方法,该递归在每个步骤中分为两个部分,其结构如下:
void recursive_function(int threads_to_use)
{
if(threads_to_use == 1) {
recursive_function(1);
recursive_function(1);
} else {
int half = threads_to_use / 2;
thread th(recursive_function, half);
recursive_function(threads_to_use - half);
th.join();
}
}
这不是理想的解决方案,但它是一个不错的解决方案,并且如果可以同时完成两个调用,则相对容易地应用于现有的单线程设计。
std::async
如果您的C ++库提供了良好的实现,那么使用异步函数调用可能比执行低级线程创建更好。线程太多或根本不执行多线程),因此我真的不建议尝试学习使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句