Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Author-XAgent Smith*/
- /*Dot product using thread*/
- /*Oct 16,2018*/
- /*Creating 4 threads where each thread will compute 4 elements in consecutive order */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <pthread.h>
- #define NUM_THRED 4
- typedef struct
- {
- double *vectorA;
- double *vectorB;
- double sum;
- int length;
- }vectorinfo;
- typedef struct
- {
- vectorinfo *info;
- int begining_index;
- }Product;
- pthread_mutex_t mutexsum;//Act as key
- void dot_product(void *prod)
- {
- printf("\n%d",pthread_self());
- Product *product =(Product*)prod;
- vectorinfo *vecinfo=product->info;
- int start=product->begining_index;
- int end=start+vecinfo->length;
- double total=0.0;
- for(int i=start;i<end;i++) total+=(vecinfo ->vectorA[i])*(vecinfo->vectorB[i]);
- pthread_mutex_lock(&mutexsum);
- vecinfo->sum=total;
- pthread_mutex_unlock(&mutexsum);
- usleep(2000);
- pthread_exit((void*)0);
- }
- int main()
- {
- vectorinfo vec;
- 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};
- 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};
- //double sum;
- vec.vectorA=VectorA;
- vec.vectorB=VectorB;
- vec.length=4;
- pthread_t threads[NUM_THRED];
- void *status;
- pthread_attr_t attr;
- pthread_mutex_init(&mutexsum,NULL);
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
- int Return;
- int num;
- for(num=0;num<NUM_THRED;num++)
- {
- Product *product=(Product*)malloc(sizeof(Product));
- product->info=&vec;
- product->begining_index=num*4;
- Return=pthread_create(&threads[num], &attr,dot_product, (void*)product);
- if(Return) {printf("ERROR:Unable to creat thread:%d",Return); exit(-1);}
- }
- pthread_attr_destroy(&attr);
- for(int i=0;i<NUM_THRED;i++)
- {
- pthread_join(&threads[i],(void**)&status);
- }
- pthread_mutex_destroy(&mutexsum);
- usleep(2000);
- printf("\nDot product sum=%lf",vec.sum);
- pthread_exit(NULL);
- return 0;
- }
Add Comment
Please, Sign In to add comment