Guest User

Untitled

a guest
Oct 21st, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define NUMTHREADS 4
  5. #define VECLEN 100
  6.  
  7. typedef struct {
  8. double *a;
  9. double *b;
  10. double sum;
  11. int veclen;
  12. } DOTDATA;
  13. DOTDATA dotstr;
  14. pthread_t call_thread[NUMTHREADS];
  15. pthread_mutex_t mutexsum;
  16.  
  17. void *dotprod(void *arg) {
  18. int i, start, end, len, offset;
  19. double mysum, *x, *y;
  20.  
  21. offset = (long)arg;
  22. len = dotstr.veclen;
  23. start = offset * len; end = start + len;
  24. x = dotstr.a; y = dotstr.b;
  25.  
  26. mysum = 0;
  27. for (i = start; i < end ; i++) {
  28. mysum += (x[i] * y[i]);
  29. }
  30.  
  31. // dotstr.sum is the shared data, must be protected.
  32. pthread_mutex_lock (&mutexsum);
  33. dotstr.sum += mysum;
  34. pthread_mutex_unlock (&mutexsum);
  35.  
  36. pthread_exit((void*) 0);
  37. }
  38.  
  39. int main (int argc, char *argv[])
  40. {
  41. long i;
  42. double *a, *b;
  43. void *status;
  44. pthread_attr_t attr;
  45.  
  46. // initialize data
  47. a = (double*)malloc(NUMTHREADS * VECLEN * sizeof(double));
  48. b = (double*)malloc(NUMTHREADS * VECLEN * sizeof(double));
  49. for (i = 0; i < VECLEN * NUMTHREADS; i++) {
  50. a[i] = b[i] = 1.0;
  51. }
  52. dotstr.veclen = VECLEN;
  53. dotstr.a = a;
  54. dotstr.b = b;
  55. dotstr.sum=0;
  56.  
  57. // initialize mutex
  58. pthread_mutex_init(&mutexsum, NULL);
  59. pthread_attr_init(&attr);
  60. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  61.  
  62. // create thread to calc products
  63. for (i = 0; i < NUMTHREADS; i++) {
  64. pthread_create(&call_thread[i], &attr, dotprod, (void*)i);
  65. }
  66.  
  67. pthread_attr_destroy(&attr);
  68. for (i = 0; i < NUMTHREADS; i++) {
  69. pthread_join(call_thread[i], &status);
  70. }
  71. printf("Sum = %f\n", dotstr.sum);
  72.  
  73. free(a); free (b);
  74. pthread_mutex_destroy(&mutexsum);
  75. pthread_exit(NULL);
  76. }
Add Comment
Please, Sign In to add comment