在Linux环境下,实现随机生成几千万个整数,然后使用多线程技术对它们排序。 请编写程序实现
时间: 2023-02-28 14:56:57 浏览: 229
你可以使用以下代码实现在 Linux 环境下生成整数并使用多线程技术进行排序:
```
#include <iostream>
#include <random>
#include <thread>
#include <vector>
#include <algorithm>
void sortPart(std::vector<int>::iterator start, std::vector<int>::iterator end) {
std::sort(start, end);
}
int main() {
std::vector<int> numbers(10000000);
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_int_distribution<int> distribution(0, 100000000);
for (auto &number : numbers) {
number = distribution(generator);
}
int threadCount = std::thread::hardware_concurrency();
std::vector<std::thread> threads;
int chunkSize = numbers.size() / threadCount;
for (int i = 0; i < threadCount; ++i) {
auto start = numbers.begin() + i * chunkSize;
auto end = numbers.begin() + (i + 1) * chunkSize;
if (i == threadCount - 1) {
end = numbers.end();
}
threads.emplace_back(sortPart, start, end);
}
for (auto &thread : threads) {
thread.join();
}
std::sort(numbers.begin(), numbers.end());
return 0;
}
```
这段代码生成了 10000000 个随机整数,然后使用 std::mt19937 生成器生成随机数。接下来,它使用 std::thread::hardware_concurrency() 获取系统的线程数,然后将生成的整数分为若干块,并使用多线程进行排序。最后,它对所有线程的结果进行最终排序。