多线程排序_如何使用多个线程进行排序以更快地运行?

多线程排序

sort supports --parallel N to run N thread. However, it seems it only uses around 100% CPU as I observed although the command specified that N threads can be used.

sort支持--parallel N运行N 线程 。 但是,尽管该命令指定可以使用N个线程,但据我观察,它似乎仅使用大约100%的CPU。

The command is as follows

命令如下

cat large-file | sort --parallel `nproc`

where I have 16 from nproc.

我有16个来自nproc

How to make sort use multiple threads to run faster?

如何使排序使用多个线程来更快地运行?

It is pos

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用多线程实现冒泡排序算法的 C++ 程序示例: ```cpp #include <iostream> #include <thread> #include <vector> using namespace std; void bubble_sort(int arr[], int start, int end) { // 冒泡排序实现 for (int i = start; i < end - 1; i++) { for (int j = start; j < end - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr[j], arr[j + 1]); } } } } void merge(int arr[], int start, int mid, int end) { int i, j, k; int n1 = mid - start + 1; int n2 = end - mid; int L[n1], R[n2]; for (i = 0; i < n1; i++) { L[i] = arr[start + i]; } for (j = 0; j < n2; j++) { R[j] = arr[mid + 1 + j]; } i = 0; j = 0; k = start; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void parallel_bubble_sort(int arr[], int n, int num_threads) { int chunk_size = n / num_threads; vector<thread> threads; for (int i = 0; i < num_threads; i++) { int start = i * chunk_size; int end = (i == num_threads - 1) ? n : (i + 1) * chunk_size; threads.push_back(thread(bubble_sort, arr, start, end)); } for (auto& t : threads) { t.join(); } for (int i = 0; i < num_threads - 1; i++) { int start = i * chunk_size; int mid = (i + 1) * chunk_size - 1; int end = (i == num_threads - 2) ? n - 1 : (i + 2) * chunk_size - 1; merge(arr, start, mid, end); } } int main() { int arr[] = {5, 2, 8, 3, 6, 1, 9, 4, 7}; int n = sizeof(arr) / sizeof(arr[0]); int num_threads = 4; parallel_bubble_sort(arr, n, num_threads); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; } ``` 在 `parallel_bubble_sort` 函数中,我们将排序过程并行化,将排序过程分成多个部分,每个部分在一个线程中执行。为了使每个线程处理的数据量相等,我们将数组分成 `num_threads` 个块,每个线程处理一个块。在排序完成后,我们使用归并排序算法将各个块的结果合并起来得到最终结果。该程序中使用了 C++11 中的线程库 `thread` 和向量 `vector`。 运行结果为: ``` 1 2 3 4 5 6 7 8 9 ``` 注意:多线程实现的冒泡排序并不一定比单线程实现,因为线程间的切换和归并操作会带来额外的开销。对于较小的数组,单线程实现可能

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值