使用C++中的pthreads求解超大数组中的最大元素
问题陈述
给定一个超大整数数组,使用多线程在数组中查找最大值
示例
如果输入数组为{10, 14, -10, 8, 25, 46, 85, 1673, 63, 65, 93, 101, 125, 50, 73, 548},则
该数组中的最大元素为1673
算法
- 把数组大小称为total_elements
- 创建N个线程
- 每个线程将处理(total_elementes/N)个数组元素,并从中找出最大元素。
- 最后,从每个线程报告的最大值中计算出最大值。
示例
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <limits.h> #define MAX 10 #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) typedef struct struct_max { int start; int end; int thread_num; } struct_max; int arr[] = {10, 14, -10, 8, 25, 46, 85, 1673, 63, 65, 93, 101, 125, 50, 73, 548}; int max_values_from_threds[MAX]; void *thread_fun(void *arg) { struct_max *s_max = (struct_max*)arg; int start = s_max->start; int end = s_max->end; int thread_num = s_max->thread_num; int cur_max_value = INT_MIN; for (int i = start; i < end; ++i) { if (arr[i] > cur_max_value) { cur_max_value = arr[i]; } } max_values_from_threds[thread_num] = cur_max_value; return NULL; } int main() { int total_elements = SIZE(arr); int n_threads = 4; struct_max thread_arr[4]; for (int i = 0; i < 4; ++i) { thread_arr[i].thread_num = i + 1; thread_arr[i].start = i * 4; thread_arr[i].end = thread_arr[i].start + 4; } pthread_t threads[4]; for (int i = 0; i < 4; ++i) { pthread_create(&threads[i], NULL, thread_fun, &thread_arr[i]); } for (int i = 0; i < 4; ++i) { pthread_join(threads[i], NULL); } int final_max_val = max_values_from_threds[0]; for (int i = 0; i < n_threads; ++i) { if (max_values_from_threds[i] > final_max_val) { final_max_val = max_values_from_threds[i]; } } printf("Maximum value = %d\n", final_max_val); return 0; }
输出
编译并执行上述程序时,会生成以下输出 -
Maximum value = 1673
广告