Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <iostream>
  4. #include <algorithm>
  5. #include <pthread.h>
  6. #include <cmath>
  7. #include<stdio.h>
  8.  
  9. // Zrobić 2 zadania z Lab 7 w instrukcji.
  10.  
  11. std::vector<int> * primes = NULL;
  12. pthread_mutex_t * mutex = NULL;
  13.  
  14. typedef struct job {
  15. int num;
  16. } job;
  17.  
  18. void cache_prime(int prime) {
  19. pthread_mutex_lock(mutex);
  20. primes->push_back(prime);
  21. pthread_mutex_unlock(mutex);
  22. }
  23.  
  24. void * worker(void * params) {
  25. int target = ((job *)params)->num;
  26. printf("Calculating: %d \n", target);
  27. //std::cout << "Calculating: " << target << std::endl;
  28.  
  29. for (int i = 2; i < target; i++) {
  30. if (target % i == 0) {
  31. printf("%d is not prime.\n", target);
  32. //std::cout << target << " is not prime..." << std::endl;
  33. return NULL;
  34. }
  35. }
  36. printf("%d is prime! \n", ((job *)params)->num);
  37. //std::cout << ((job *)params)->num << " is prime!" << std::endl;
  38. cache_prime(((job *)params)->num);
  39. return NULL;
  40. }
  41.  
  42. int main() {
  43. int from = 4, to = 100;
  44.  
  45. mutex = new pthread_mutex_t;
  46. primes = new std::vector<int>();
  47.  
  48. pthread_mutex_init(mutex, NULL);
  49. pthread_t * threads[4] = { NULL };
  50. job * jobs[4] = { NULL };
  51.  
  52. if (from > to) std::swap(from, to);
  53. if (from <= 1) from = 2;
  54. if (to <= 1) to = 2;
  55. printf("Looking for primes between %d and %d (inclusive)...\n", from, to);
  56. //std::cout << "Looking for primes between " << from << " and " << to << " (inclusive)..." << std::endl;
  57.  
  58. for (int i = from; i <= to; i++) {
  59. int thread_index = (i - from) % 4;
  60. if (threads[thread_index] != NULL) {
  61. pthread_join((*threads[thread_index]), NULL);
  62.  
  63. delete threads[thread_index];
  64. free(jobs[thread_index]);
  65. threads[thread_index] = NULL;
  66. }
  67.  
  68. job * work = (job *)malloc(sizeof(work));
  69. work->num = i;
  70.  
  71. threads[thread_index] = new pthread_t;
  72. pthread_create(threads[thread_index], NULL, worker, work);
  73. jobs[thread_index] = work;
  74. }
  75.  
  76. for (int i = 0; i < 4; i++) {
  77. if (threads[i] != NULL) pthread_join((*threads[i]), NULL);
  78. }
  79.  
  80. for (int i = 0; i < primes->size(); i++)
  81. printf("%d, ", primes->data()[i]);
  82. printf("done.\n")
  83. //std::cout << "done." << std::endl;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement