Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. //--------------------------------------------
  2. // NAME: Antonio Milev
  3. // CLASS: XIb
  4. // NUMBER: 02
  5. // PROBLEM: #1
  6. // FILE NAME: primes.cc
  7. // FILE PURPOSE:
  8. // Calculates how many prime numbers are there between
  9. // 1 and n using multythreading.
  10. //---------------------------------------------
  11. #include <stdio.h>
  12. #include <pthread.h>
  13. #include <string.h>
  14. #include <stdlib.h>
  15.  
  16. void *calc_prime(void *nd);
  17.  
  18. #define NUM_THREADS 1000
  19.  
  20. int main() {
  21. char input[200];
  22. pthread_t threads[NUM_THREADS];
  23. int tr_index = 0;
  24. while(1) {
  25. scanf("%s",input);
  26. if(strcmp(input, "e") == 0) {
  27. for(int t = 0;t < tr_index;t++) {
  28. pthread_join(threads[t], NULL);
  29. }
  30. break;
  31. } else if(strcmp(input, "p") == 0) {
  32. int n;
  33. scanf("%d",&n);
  34. int rc = pthread_create(&threads[tr_index], NULL, calc_prime, (void*)n);
  35. tr_index++;
  36. } else {
  37. printf("Supported commands:\np N - Starts a new calculation for the number of primes from 1 to N\ne - Waits for all calculations to finish and exits\n");
  38. }
  39. }
  40. }
  41.  
  42. //--------------------------------------------
  43. // FUNCTION: calc_prime
  44. // Calculates how many prime numbers are there between 1 and num
  45. // PARAMETERS:
  46. // num - the number to which we calculate
  47. //----------------------------------------------
  48. void *calc_prime(void *num) {
  49. int n = (int)num;
  50. printf("Prime calculation started for N=%d\n",n);
  51. int prime_counter = 0;
  52. int is_prime = 1;
  53. for(int i = 2;i < n;i++) {
  54. for(int j = 2;j < i;j++) {
  55. is_prime = 1;
  56. if(i % j == 0) {
  57. is_prime = 0;
  58. break;
  59. }
  60. }
  61. if(is_prime) {
  62. prime_counter++;
  63. }
  64. }
  65. printf("Number of primes for N=%d is %d\n",n,prime_counter);
  66. pthread_exit(NULL);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement