You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

87 lines
2.1 KiB

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int is_prime(int n) {
  5. if (n <= 1)
  6. return 0;
  7. for (int d = 2; d * d <= n; d++)
  8. if (n % d == 0)
  9. return 0;
  10. return 1;
  11. }
  12. int n = 0;
  13. // You will be locking and unlocking this
  14. pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER;
  15. // Don't modify these variables directly, use the functions below.
  16. int next_number_to_check = 0;
  17. int primes_found_so_far = 0;
  18. int get_number_to_check() {
  19. int ret = next_number_to_check;
  20. if (next_number_to_check != n)
  21. next_number_to_check++;
  22. return ret;
  23. }
  24. void increment_primes() { primes_found_so_far++; }
  25. void *check_primes(void *arg) {
  26. /*
  27. TODO
  28. Complete this function. This function loops forever, continuously taking a
  29. value from get_number_to_check and, if it turns out to be prime,
  30. increments the global prime counter with increment_primes. Once
  31. get_number_to_check returns <n>, the function exits. Pay close attention
  32. to your use of the global mutex.
  33. */
  34. while(1) {
  35. pthread_mutex_lock(&global_lock);
  36. int num = get_number_to_check();
  37. pthread_mutex_unlock(&global_lock);
  38. if (is_prime(num)) {
  39. pthread_mutex_lock(&global_lock);
  40. increment_primes();
  41. pthread_mutex_unlock(&global_lock);
  42. }
  43. if (num == n)
  44. return NULL;
  45. }
  46. }
  47. int main(int argc, char *argv[]) {
  48. int n_threads = atoi(argv[2]);
  49. n = atoi(argv[1]);
  50. pthread_mutex_init(&global_lock, NULL);
  51. pthread_t *threads = malloc(n_threads * sizeof(pthread_t));
  52. for (int i = 0; i < n_threads; i++) {
  53. /*
  54. TODO
  55. Spawn <n_threads> threads.
  56. */
  57. pthread_create(&threads[i], NULL, &check_primes, NULL);
  58. }
  59. for (int i = 0; i < n_threads; i++) {
  60. /*
  61. TODO
  62. Join the threads.
  63. */
  64. pthread_join(threads[i], NULL);
  65. }
  66. /*
  67. TODO
  68. Free the allocated memory.
  69. */
  70. pthread_mutex_destroy(&global_lock);
  71. free(threads);
  72. printf("%d\n", primes_found_so_far);
  73. exit(EXIT_SUCCESS);
  74. }