Advertisement
EBobkunov

ex4 w5

Oct 9th, 2023
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <pthread.h>
  5.  
  6. // Function to check primality (from ex3)
  7. bool is_prime(int n);
  8.  
  9. // The mutexes
  10. pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER;
  11. pthread_mutex_t k_lock = PTHREAD_MUTEX_INITIALIZER;
  12. pthread_mutex_t c_lock = PTHREAD_MUTEX_INITIALIZER;
  13.  
  14. // Do not modify these variables directly, use the functions below.
  15. int k = 0;
  16. int c = 0;
  17. int n = 0;
  18.  
  19. // Get the next prime candidate
  20. int get_number_to_check() {
  21.     int ret;
  22.     pthread_mutex_lock(&k_lock);
  23.     ret = k;
  24.     if (k != n) {
  25.         k++;
  26.     }
  27.     pthread_mutex_unlock(&k_lock);
  28.     return ret;
  29. }
  30.  
  31. // Increment the prime counter
  32. void increment_primes() {
  33.     pthread_mutex_lock(&c_lock);
  34.     c++;
  35.     pthread_mutex_unlock(&c_lock);
  36. }
  37.  
  38. // Start routine
  39. void *check_primes(void *arg) {
  40.     while (1) {
  41.         int num = get_number_to_check();
  42.         if (num >= n) break; // All numbers checked
  43.         if (is_prime(num)) {
  44.             increment_primes();
  45.         }
  46.     }
  47.     return NULL;
  48. }
  49.  
  50. int main(int argc, char *argv[]) {
  51.     if (argc != 3) {
  52.         fprintf(stderr, "Usage: %s n m\n", argv[0]);
  53.         return 1;
  54.     }
  55.  
  56.     n = atoi(argv[1]);
  57.     int m = atoi(argv[2]);
  58.  
  59.     pthread_t threads[m];
  60.  
  61.     // Create threads
  62.     for (int i = 0; i < m; i++) {
  63.         pthread_create(&threads[i], NULL, check_primes, NULL);
  64.     }
  65.  
  66.     // Join threads
  67.     for (int i = 0; i < m; i++) {
  68.         pthread_join(threads[i], NULL);
  69.     }
  70.  
  71.     // Print the final result
  72.     printf("Number of primes in [0, %d) = %d\n", n, c);
  73.  
  74.     return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement