Advertisement
Guest User

threads

a guest
Feb 19th, 2020
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <iostream>
  7. #include <sys/time.h> //measure the execution time of the computations
  8.  
  9. using namespace std;
  10.  
  11. //The number of thread to be generated
  12. #define NUMBER_OF_THREADS 4
  13.  
  14. void * Prime(void* index);
  15.  
  16. long numbers[4] = {2500000, 5000000, 7500000, 10000000};
  17. long start_numbers[4] = {2, 2500001, 5000001, 7500001};
  18.  
  19. int thread_numbers[4] = {0, 1, 2, 3};
  20.  
  21. int main(){
  22. pthread_t tid[NUMBER_OF_THREADS];
  23.  
  24. int tn;
  25.  
  26. long sum = 0;
  27.  
  28. timeval start_time, end_time;
  29.  
  30. double start_time_microseconds, end_time_microseconds;
  31.  
  32. gettimeofday(&start_time, NULL);
  33.  
  34. start_time_microseconds = start_time.tv_sec * 10000000 + start_time.tv_usec;
  35. for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
  36. if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
  37. perror("thread fail");
  38. exit(-1);
  39. }
  40. }
  41. long value[4];
  42.  
  43. for(int i = 0; i < NUMBER_OF_THREADS; i++){
  44. if(pthread_join(tid[i],(void **) &value[i]) == 0){
  45. sum = sum + value[i]; //add four sums together
  46. }else{
  47. perror("Thread join failed");
  48. exit(-1);
  49. }
  50. }
  51. //get the end time in microseconds
  52. gettimeofday(&end_time, NULL);
  53.  
  54. end_time_microseconds = end_time.tv_sec * 10000000 + end_time.tv_usec;
  55.  
  56. //calculate the time passed
  57. double time_passed = end_time_microseconds - start_time_microseconds;
  58.  
  59. cout << "Sum is: " << sum << endl;
  60. cout << "Running time is: " << time_passed << " microseconds" << endl;
  61.  
  62. exit(0);
  63. }
  64.  
  65.  
  66. //Prime function
  67. void* Prime(void* index){
  68. int temp_index;
  69.  
  70. temp_index = *((int*)index);
  71. long sum_t = 0;
  72.  
  73. for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
  74. for (int j=2; j*j <= i; j++)
  75. {
  76. if (i % j == 0)
  77. {
  78. break;
  79. }
  80. else if (j+1 > sqrt(i)) {
  81. sum_t++;
  82. }
  83. }
  84.  
  85. }
  86.  
  87. cout << "Thread " << temp_index << " terminates" << endl;
  88. pthread_exit( (void*) sum_t);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement