Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5.  
  6. #define NUM_THREADS 4
  7. #define TOT_COUNT 100000000
  8.  
  9. float randNumGen(){
  10.  
  11.  
  12. int random_value = rand();
  13. float unit_random = random_value / (float) RAND_MAX; //m
  14. return unit_random;
  15. }
  16.  
  17. void *doCalcs(void *threadid)
  18. {
  19. long longTid;
  20. longTid = (long)threadid;
  21.  
  22. int tid = (int)longTid;
  23.  
  24. float *in_count = (float *)malloc(sizeof(float));
  25. *in_count=0;
  26.  
  27. float tot_iterations= TOT_COUNT/NUM_THREADS;
  28.  
  29. int counter=0;
  30.  
  31. for(counter=0;counter<tot_iterations;counter++){
  32. float x = randNumGen();
  33. float y = randNumGen();
  34.  
  35. float result;
  36. result = sqrt((x*x) + (y*y));
  37.  
  38. if(result<1){
  39. *in_count+=1;
  40. }
  41.  
  42. }
  43.  
  44. if(tid==0){
  45. float remainder = TOT_COUNT%NUM_THREADS;
  46.  
  47. for(counter=0;counter<remainder;counter++){
  48. float x = randNumGen();
  49. float y = randNumGen();
  50.  
  51. float result;
  52. result = sqrt((x*x) + (y*y));
  53.  
  54. if(result<1){
  55. *in_count+=1;
  56. }
  57. }
  58. }
  59. pthread_exit((void *)in_count);
  60. }
  61.  
  62. int main(int argc, char *argv[])
  63. {
  64. pthread_t threads[NUM_THREADS];
  65. int rc;
  66. long t;
  67. void *status;
  68. float tot_in=0;
  69.  
  70. for(t=0;t<NUM_THREADS;t++){
  71. rc = pthread_create(&threads[t], NULL, doCalcs, (void *)t);
  72. if (rc){
  73. printf("ERROR; return code from pthread_create() is %d\n", rc);
  74. exit(-1);
  75. }
  76. }
  77.  
  78. for(t=0;t<NUM_THREADS;t++){
  79.  
  80. pthread_join(threads[t], &status);
  81.  
  82. tot_in+=*(float*)status;
  83.  
  84. }
  85. printf("Value for Pi is %f \n",4*(tot_in/TOT_COUNT));
  86.  
  87. pthread_exit(NULL);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement