简体   繁体   中英

How to return an array in c using pthreads?

I tried to write a program that a thread returns an array of numbers by passing a random vector to the thread and thread returns 2 times of the vector. The program is running fine put I'm not getting the expected output. The code is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}    

   pthread_exit(sum[i]);
}

int main()
{

 double total = omp_get_wtime();

 printf("This is using PThread\n");

  pthread_t tid1;
  pthread_create(&tid1, NULL, myThreaddouble, NULL);
  printf("Double of the vector:-   \n");
  for ( i = 0 ; i < 5 ; i++ )
  {
    printf(" %d\n",(int) sum[i]);
  }
  pthread_join(tid1, sum[i]);

  total = omp_get_wtime() - total;
  printf("%lf is time to add\n",total);
  printf("\n");

  return 0;

}

and the output is as follows:

This is using PThread
Double of the vector:-   
 0
 0
 0
 0
 0
0.000188 is time to add

Which is not the expected output, so can someone tell me what is the mistake in this code and how to return an array using pthread. In the i should be able to sum all the return values.

I used gcc qc -lpthread -lrt -fopenmp command to compile this program.

Thank you in advance!

Probably the problem is being caused because of the line int *sum[10]; in this function:

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}

You are creating a local variable sum , which will have preference over the global variable sum , since it is in a inner scope. Try removing it.

There you go. I have taken liberty to comment out the time calculation part.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble(void *a)
{

//int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}    

   //pthread_exit(sum[i]);
   pthread_exit(NULL);
}

int main()
{

// double total = omp_get_wtime();

 printf("This is using PThread\n");

  pthread_t tid1;
  pthread_create(&tid1, NULL, myThreaddouble, NULL);
  printf("Double of the vector:-   \n");

  //pthread_join(tid1, sum[i]);
  pthread_join(tid1, NULL);

  for ( i = 0 ; i < 5 ; i++ )
  {
    printf(" %d\n",(int) sum[i]);
  }
 // pthread_join(tid1, sum[i]);

  //total = omp_get_wtime() - total;
  //printf("%lf is time to add\n",total);
  printf("\n");

  return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM