Advertisement
EBobkunov

ex3 w5

Oct 9th, 2023
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <pthread.h>
  5. #include <time.h>
  6.  
  7. // Function to check primality
  8. bool is_prime(int n) {
  9.     if (n <= 1) return false;
  10.     int i = 2;
  11.     for (; i * i <= n; i++) {
  12.         if (n % i == 0)
  13.             return false;
  14.     }
  15.     return true;
  16. }
  17.  
  18. // Struct to hold prime request
  19. typedef struct prime_request {
  20.     int a, b;
  21.     int count;
  22. } prime_request;
  23.  
  24. // Thread function to count primes in a subinterval
  25. void *prime_counter(void *arg) {
  26.     prime_request *req = (prime_request *)arg;
  27.     int count = 0;
  28.     for (int i = req->a; i < req->b; i++) {
  29.         if (is_prime(i))
  30.             count++;
  31.     }
  32.     req->count = count;
  33.     return NULL;
  34. }
  35.  
  36. int main(int argc, char *argv[]) {
  37.     if (argc != 3) {
  38.         fprintf(stderr, "Usage: %s n m\n", argv[0]);
  39.         return 1;
  40.     }
  41.  
  42.     int n = atoi(argv[1]);
  43.     int m = atoi(argv[2]);
  44.  
  45.     pthread_t threads[m];
  46.     prime_request requests[m];
  47.     int subinterval_size = n / m;
  48.     int prime_count = 0;
  49.  
  50.     // Create threads and distribute work
  51.     for (int i = 0; i < m; i++) {
  52.         requests[i].a = i * subinterval_size;
  53.         requests[i].b = (i == m - 1) ? n : (i + 1) * subinterval_size;
  54.         pthread_create(&threads[i], NULL, prime_counter, &requests[i]);
  55.     }
  56.  
  57.     // Wait for threads to finish
  58.     for (int i = 0; i < m; i++) {
  59.         pthread_join(threads[i], NULL);
  60.         prime_count += requests[i].count;
  61.     }
  62.  
  63.     printf("Number of primes in [0, %d) = %d\n", n, prime_count);
  64.  
  65.     return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement