编辑代码

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_THREADS 8
#define MIN_BLOCK_SIZE 30
typedef int bool;
#define true 1
#define false 0

typedef struct 
{
    float *start;
    int len;
    int block_size;
    double sum;
}Sum_arg;

int thrd_num = 0;
void* parallel_sum(void* arg);

bool sum (float arr[], int len, double* sumPtr)
{
    int block_size = len / MAX_THREADS;
    if ( block_size < MIN_BLOCK_SIZE)
        block_size = MIN_BLOCK_SIZE;
    Sum_arg args = { arr, len, block_size, 0.0};
    if (parallel_sum( &args)){
        *sumPtr = args.sum;
        return true;
    }
    else
        return false;
}

void* parallel_sum(void * arg)
{
    int i = 0;
    
    pthread_t ntid;
    Sum_arg *argp = (Sum_arg*)arg;
    if(argp->len <= argp->block_size){
        for( i = 0; i < argp->len; i++){
            argp->sum += argp->start[i];
           
        }
         return (void*)1;
    }
    else{
        int mid = argp->len / 2;
        Sum_arg arg2 = {argp->start+mid, argp->len-mid, argp->block_size, 0.0};

        argp->len = mid;
        
        int* res = NULL;
        if( pthread_create( &ntid, NULL, parallel_sum, arg) != 0){
            printf(" create thread_id=0x%lx, thread num= %d fail \n", pthread_self(), ++thrd_num);
            return (void*)0;
        }
        else{
            printf(" create thread_id=0x%lx, thread num= %d sucess \n",  pthread_self(), ++thrd_num);
        }
        if(!parallel_sum(&arg2)){
            printf("detach thread_id=0x%lx, thread num= %d sucess \n",  pthread_self(), --thrd_num);
            pthread_detach(ntid);
            return (void*)0;
        }
        pthread_join(ntid, (void**)&res);
        if(!res)  {            
            printf("join thread_id=0x%lx, thread num= %d fail \n",  pthread_self(), --thrd_num);
            return (void*)0;
        }
        else{
            printf("join thread_id=0x%lx, thread num= %d success \n", pthread_self(), --thrd_num);
        }
        argp->sum +=arg2.sum;
        return (void*)1;
    }
    return (void*)1;
}

#define MAX_NUM_LEN 1000
/*本文件最主要的是实现了从txt文件中读取了float类型数据*/

int main(void) 
{
 double sum_value;
 float p[MAX_NUM_LEN]= {0};
 FILE* frp1 =NULL;
 FILE* frp_out = NULL;
 int i = 0, j;
 if( (frp1 = fopen("p.txt", "r") )== NULL){
     printf("txt文件打开失败 \n");
     exit(0);
 }
while (!feof(frp1))
    fscanf(frp1, "%f", p + i++);

printf("@@ i = %d \n", i);

for(j = 0; j < i ; printf("%.1f ", p[j++]));    
printf("\n");

printf("i=%d, j=%d \n", i , j);
fclose(frp1); 

if((frp_out = fopen("out.txt", "w")) == NULL){
    printf("out.txt open failed \n");
    exit(0);
}
for(j = 0; j < i; j++){
    fprintf(frp_out, "%.1f ", p[j]);
    if(j != 0 && j%14 ==0){
        fprintf(frp_out, "%s", "\n");
    }
}
fclose(frp_out);

sum(p, i-1, &sum_value );
printf("sum_value = %f \n", sum_value);

return 0;
}