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.62 KB | None | 0 0
  1. //------------------------------------------------------------------------
  2. // NAME: Daniel Yanev
  3. // CLASS: XIa
  4. // NUMBER: 8
  5. // FILE NAME: main.c (unix file name)
  6. //------------------------------------------------------------------------
  7.  
  8. #include <stdio.h>
  9. #include <pthread.h>
  10. #include <unistd.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13.  
  14. int calc_prime(int a){
  15. for(int i = a - 1; i >= 2; i--){
  16. if(a % i == 0) return 0;
  17. }
  18. return 1;
  19. }
  20.  
  21. void * calc(void * a){
  22. int * n = (int*)a;
  23. printf("Prime calculation started for N=%d\n", *n);
  24. ssize_t count = 0;
  25. for(int i = 2; i < *n; i++){
  26. if(calc_prime(i)){
  27. // printf("%d is prime, count %ld\n", i, count);
  28. count++;
  29. }
  30. }
  31. printf("Number of primes for N=%d is %ld", *n, count);
  32. }
  33.  
  34. int main(){
  35.  
  36. char a;
  37. char *line = NULL;
  38. size_t len = 0;
  39. ssize_t nread;
  40. void * arg[100];
  41. int counter = 0;
  42. pthread_t threads[100];
  43.  
  44.  
  45.  
  46. while((nread = getline(&line, &len, stdin)) != -1){
  47. line[strlen(line) - 1] = '\0';
  48. if(strcmp(line, "e") == 0){
  49. break;
  50. } else if(line[0] == 'p'){
  51. int number;
  52. sscanf(line + 2, "%d", &number);
  53. //printf("Number %d\n", number);
  54. int rc = pthread_create(&threads[counter++], NULL, calc((void*)&number), NULL);
  55. if(rc){
  56. printf("Err for pthread create\n");
  57. }
  58. } else {
  59. 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");
  60. }
  61.  
  62. // printf("Before\n");
  63. } // END OF WHILE LOOP
  64.  
  65. free(line);
  66. pthread_exit(0);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement