pthread函数的返回值与函数

时间:2015-12-09 20:30:34

标签: c++ pthreads

现在我正在尝试使用pthread函数返回值。在下面的代码中,我想得到的输出是“38 99”或“99 38”,但程序输出“99 99”或“38 38”。 当我在pthread函数中放入“cout”时,输出是正确的,但是当我在主函数中输入“cout”时,输出是错误的。谁能帮我检查一下我做错了什么?

using namespace std;

#define NTHREADS 2
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

struct args{
  int * numbers;
  float result;
};

void *add(void* a){
   struct args *number = (struct args *)a;
   pthread_mutex_lock( &mutex1 );
   int *n = (int*) number->numbers;
   float sum =0;
   for(int i = 0; i < 5; i++){
     sum = sum + n[i] +5;
   }
   float av = sum/5;
   number-> result  = av;
   //cout << number->result <<endl;
    pthread_mutex_unlock( &mutex1 );
   return number;  
   }

void *substract(void* a){
 struct args *number = (struct args *)a;
 pthread_mutex_lock( &mutex1 );
 int *n = (int*) number->numbers;
 float sum =0;
 for(int i = 0; i < 5; i++){
    sum = sum + n[i] *3;
 }
 float av = sum/5;
 number-> result  = av;
 //  cout << number->result <<endl;
 pthread_mutex_unlock( &mutex1 );

 return number;
}

main(){
pthread_t thread_id[NTHREADS];
int i, j;

int *numbers = new int[5];
numbers[0] = 34; numbers[1] = 2; numbers[2]= 77; numbers[3] = 40; numbers[4] = 12;

struct args a;
a.numbers = numbers;
pthread_create( &thread_id[0], NULL, add, (void*) &a);
pthread_create( &thread_id[1], NULL, substract, (void*) &a );
void *status1;
void * status2;

pthread_join( thread_id[0], &status1);
pthread_join( thread_id[1], &status2);
args status = *(args*) status1;
float ra = status.result;
cout << ra << endl;

args statuss = *(args*) status2;
float rb = statuss.result;
cout << rb << endl;

 exit(EXIT_SUCCESS);
}

1 个答案:

答案 0 :(得分:3)

你得到这个输出是因为两个线程都将结果写到同一个地方 - struct args a

您需要在main函数中分配两个 struct args,并将一个地址传递给第一个线程,另一个传递给第二个线程。