一、直接使用版本
#include <iostream>
#include <vector>
#include <math.h>
#include <thread>
#include <chrono>
// 计算函数,将平方计算分散到多个线程中
void calculate_square_multithread(std::vector<int>& nums, int num_threads) {
int task_count = nums.size() / num_threads;
std::vector<std::thread> threads(num_threads);
for (int i = 0; i < num_threads; ++i) {
int start = i * task_count;
int end = (i + 1) * task_count;
threads[i] = std::thread([&nums, start, end]() {
for (int j = start; j < end; ++j) {
nums[j] *= nums[j];
}
});
}
for (auto& t : threads) {
t.join();
}
}
// 计算函数,使用单线程计算数组的平方
void calculate_square_singlethread(std::vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
-1.0f * logf((i * i * 1.0f / 10) - 1.0f);
-1.0f * logf((i * i * 1.0f / 10) - 1.0f);
-1.0f * logf((i * i * 1.0f / 10) - 1.0f);
-1.0f * logf((i * i * 1.0f / 10) - 1.0f);
nums[i] *= nums[i];
}
}
int main() {
const int array_size = 990000000; // 数组大小
std::vector<int> nums(array_size);
// 填充数组
for (int i = 0; i < array_size; ++i) {
nums[i] = i;
}
// 使用单线程计算数组平方并计时
auto start = std::chrono::high_resolution_clock::now();
calculate_square_singlethread(nums);
auto end = std::chrono::high_resolution_clock::now();
auto duration_single = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Single thread time: " << duration_single.count() << " milliseconds" << std::endl;
// 使用多线程计算数组平方并计时,假设使用4个线程
start = std::chrono::high_resolution_clock::now();
calculate_square_multithread(nums, 4);
end = std::chrono::high_resolution_clock::now();
auto duration_multithread = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Multi-thread time: " << duration_multithread.count() << " milliseconds" << std::endl;
std::cout << "Speedup: " << duration_single.count() / duration_multithread.count() << "x" << std::endl;
return 0;
}
结果
Single thread time: 69591 milliseconds
Multi-thread time: 2193 milliseconds
Speedup: 31x
二、带返回值使用
#include <iostream>
#include <thread>
#include <vector>
#include <future>
int calculate(int value) {
// 模拟耗时计算
std::this_thread::sleep_for(std::chrono::seconds(2));
return value * value;
}
void joinFutures() {
int numThreads = 5;
std::vector<std::future<int>> futures;
for (int i = 0; i < numThreads; ++i) {
int value = i + 1;
// 创建新线程并返回其未完成状态的 future 对象
auto future = std::async([value](){
return calculate(value);
});
// 存储每个线程的 future 对象到 vector 中
futures.push_back(std::move(future));
}
// 遍历所有的 future 对象,通过 get() 函数获取结果
for (auto& future : futures) {
try {
int result = future.get();
// 输出每个线程的结果
std::cout << "Result from thread #" << result << ": ";
std::cout << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception caught in main thread: " << e.what() << std::endl;
}
}
}
int main() {
joinFutures();
return 0;
}