Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #define INTERVAL 1000000
  4. #define THNUMS 3
  5.  
  6. //thread params
  7. struct ThreadParams
  8. {
  9. int id; //id
  10. int low; //start
  11. int high; //end
  12. double ysum; //return partial sum
  13. }
  14.  
  15. #define BLOCK_LOW(id, p, n) ((id)*(n)/(p))
  16. #define BLOCK_HIGH(id, p, n) (BLOCK_LOW((id)+1,p,n)-1)
  17. #define BLOCK_SIZE(id, p, n) (BLOCK_HIGH(id,p,n)-BLOCK_LOW(id,p,n)+1)
  18.  
  19. //calculate pi partial sum
  20. void *calcpi(void *arg)
  21. {
  22. double ysum;
  23. double xi;
  24. int i;
  25.  
  26. struct ThreadParams *pm = (struct ThreadParams*)arg;
  27.  
  28. ysum = 0.0;
  29.  
  30. for(i = pm->low; i <= pm->high; i++)
  31. {
  32. xi=((1.0/INTERVALS)*(i+0.5));
  33. ysum=ysum+4.0/(1.0+xi*xi);
  34. }
  35.  
  36. pm->ysum = ysum;
  37. }
  38.  
  39. int main(int argc, char* argv[])
  40. {
  41. struct ThreadParams ptharg[THNUMS];
  42. double area;
  43. double ysum;
  44. int i;
  45.  
  46. pthread_t tid;
  47. void *status;
  48.  
  49. //create multithreads to calculate partial sum
  50. ysum = 0.0;
  51.  
  52. for(i=0; i<THNUMS; i++)
  53. {
  54. ptharg[i].id = i;
  55. ptharg[i].low = BLOCK_LOW(i,THNUMS,INTERVALS);
  56. ptharg[i].high = BLOCK_HIGH(i,THNUMS,INTERVALS);
  57.  
  58. if(pthread_create(&tid, NULL, calcpi, (void*)&ptharg[i])!=0)
  59. {
  60. perror("error creating child");
  61. return -1;
  62. }
  63.  
  64. pthread_join(tid, &status);
  65. }
  66.  
  67. //calculate total area
  68. area = 0;
  69.  
  70. for(i=0; i<THNUMS;i++)
  71. {
  72. area = area + ptharg[i].ysum;
  73. }
  74.  
  75. area = area * (1.0/INTERVALS);
  76. printf("Area is %13.11f\n",area);
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement