- 主线程创建两个辅助线程
- 辅助线程1使用选择排序算法对数组的前半部分排序
- 辅助线程2使用选择排序算法对数组的后半部分排序
- 主线程等待辅助线程运行結束后,使用归并排序算法归并子线程的计算结果
- 本题要求 1: 使用线程参数,消除程序中的代码重复
与多线程中的等待线程的列2相似;
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
int array[10]={41,67,34,58,69,24,78,58,62,64};
int sorted[10];
#define NR_TOTAL 10
#define NR_CPU 2
#define NR_CHILD (NR_TOTAL/NR_CPU)
struct param {
int *array;
int start;
int end;
};
void *compute(void *arg)
{
struct param *param;
struct result *result;
int i,j;
int tmp;
int min;
param = (struct param *)arg;
for (i = param->start; i < param->end; i++){
min = i;
for(j = i+1 ; j < param->end ; j++){
if(param->array[min] > param->array[j])
min = j;
}
tmp = param->array[i];
param->array[i] = param->array[min];
param->array[min] = tmp;
}
return 0;
}
void Merge_Array(int *array){
int i = 0 , j = NR_TOTAL/2 , k = 0;
while(i < NR_TOTAL/2 && j < NR_TOTAL){
if(array[i] < array[j])
sorted[k++]=array[i++];
else
sorted[k++]=array[j++];
}
while(i<NR_TOTAL/2)
sorted[k++]=array[i++];
while(j<NR_TOTAL)
sorted[k++]=array[j++];
}
void print(int *array){
int i;
for(i=0;i<NR_TOTAL;i++)
printf("%d ",array[i]);
printf("\n");
}
int main()
{
pthread_t workers[NR_CPU];
struct param params[NR_CPU];
int i;
struct param *param;
for (i = 0; i < NR_CPU; i++) {
param = ¶ms[i];
param->array = array;
param->start = i * NR_CHILD;
param->end = (i + 1) * NR_CHILD;
pthread_create(&workers[i], NULL, compute, param);
}
for (i = 0; i < NR_CPU; i++) {
struct result *result;
pthread_join(workers[i], NULL);
}
Merge_Array(param->array);
print(sorted);
return 0;
}
得到结果为