Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #define NTHREADS 4
  6. #define ARRAYSIZE 1000000
  7. #define ITERATIONS ARRAYSIZE / NTHREADS
  8.  
  9. double sum=0.0, a[ARRAYSIZE];
  10. pthread_mutex_t sum_mutex;
  11.  
  12.  
  13. void *do_work(void *tid)
  14. {
  15. int i, start, *mytid, end;
  16. double mysum=0.0;
  17.  
  18. /* Initialize my part of the global array and keep local sum */
  19. mytid = (int *) tid;
  20. start = (*mytid * ITERATIONS);
  21. end = start + ITERATIONS;
  22. printf ("Thread %d doing iterations %d to %dn",*mytid,start,end-1);
  23. for (i=start; i < end ; i++) {
  24. a[i] = i * 1.0;
  25. mysum = mysum + a[i];
  26. }
  27.  
  28. /* Lock the mutex and update the global sum, then exit */
  29. pthread_mutex_lock (&sum_mutex);
  30. sum = sum + mysum;
  31. pthread_mutex_unlock (&sum_mutex);
  32. pthread_exit(NULL);
  33. }
  34.  
  35.  
  36. int main(int argc, char *argv[])
  37. {
  38. int i, start, tids[NTHREADS];
  39. pthread_t threads[NTHREADS];
  40. pthread_attr_t attr;
  41.  
  42. /* Pthreads setup: initialize mutex and explicitly create threads in a
  43. joinable state (for portability). Pass each thread its loop offset */
  44. pthread_mutex_init(&sum_mutex, NULL);
  45. pthread_attr_init(&attr);
  46. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  47. for (i=0; i<NTHREADS; i++) {
  48. tids[i] = i;
  49. pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
  50. }
  51.  
  52. /* Wait for all threads to complete then print global sum */
  53. for (i=0; i<NTHREADS; i++) {
  54. pthread_join(threads[i], NULL);
  55. }
  56. printf ("Done. Sum= %e n", sum);
  57.  
  58. sum=0.0;
  59. for (i=0;i<ARRAYSIZE;i++){
  60. a[i] = i*1.0;
  61. sum = sum + a[i]; }
  62. printf("Check Sum= %en",sum);
  63.  
  64. /* Clean up and exit */
  65. pthread_attr_destroy(&attr);
  66. pthread_mutex_destroy(&sum_mutex);
  67. pthread_exit (NULL);
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement