XAgent-Smith

USING_pthread_for_dotproduct_dem

Oct 15th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. /*Author-XAgent Smith*/
  2. /*Dot product using thread*/
  3. /*Oct 16,2018*/
  4. /*Creating 4 threads where each thread will compute 4 elements in consecutive order */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <errno.h>
  9. #include <pthread.h>
  10.  
  11. #define NUM_THRED 4
  12.  
  13. typedef struct
  14. {
  15.   double *vectorA;
  16.   double *vectorB;
  17.   double sum;
  18.   int length;
  19. }vectorinfo;
  20.  
  21. typedef struct
  22. {
  23.    vectorinfo *info;
  24.    int begining_index;
  25. }Product;
  26.  
  27. pthread_mutex_t mutexsum;//Act as key
  28.  
  29.  
  30. void dot_product(void *prod)
  31. {
  32.    printf("\n%d",pthread_self());
  33.    Product *product =(Product*)prod;
  34.   vectorinfo *vecinfo=product->info;
  35.   int start=product->begining_index;
  36.   int end=start+vecinfo->length;
  37.   double total=0.0;
  38.  
  39.   for(int i=start;i<end;i++) total+=(vecinfo ->vectorA[i])*(vecinfo->vectorB[i]);
  40.  
  41.   pthread_mutex_lock(&mutexsum);
  42.  
  43.   vecinfo->sum=total;
  44.   pthread_mutex_unlock(&mutexsum);
  45. usleep(2000);
  46.  
  47.   pthread_exit((void*)0);
  48. }
  49.  
  50. int main()
  51. {
  52.    vectorinfo vec;
  53.    double VectorA[]={1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0};
  54.  
  55.     double VectorB[]={1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0};
  56.  
  57.     //double sum;
  58.    
  59.    vec.vectorA=VectorA;
  60.    vec.vectorB=VectorB;
  61.  
  62.    vec.length=4;
  63.  
  64.   pthread_t threads[NUM_THRED];
  65.   void *status;
  66.   pthread_attr_t attr;
  67.   pthread_mutex_init(&mutexsum,NULL);
  68.   pthread_attr_init(&attr);
  69.  
  70.   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  71.  
  72.   int Return;
  73.   int num;
  74.  
  75.   for(num=0;num<NUM_THRED;num++)
  76.   {
  77.  
  78.   Product *product=(Product*)malloc(sizeof(Product));
  79.    product->info=&vec;
  80.    product->begining_index=num*4;
  81.    
  82.   Return=pthread_create(&threads[num], &attr,dot_product, (void*)product);
  83.  
  84.   if(Return) {printf("ERROR:Unable to creat thread:%d",Return); exit(-1);}
  85.   }
  86. pthread_attr_destroy(&attr);
  87. for(int i=0;i<NUM_THRED;i++)
  88. {
  89.     pthread_join(&threads[i],(void**)&status);
  90.    
  91. }
  92.   pthread_mutex_destroy(&mutexsum);
  93.  usleep(2000);
  94.  printf("\nDot product sum=%lf",vec.sum);
  95.  
  96.  pthread_exit(NULL);
  97.  
  98.  
  99.  
  100.  
  101. return 0;
  102. }
Add Comment
Please, Sign In to add comment