Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <zconf.h>
  4.  
  5. #define or ||
  6. void* isPrime(void* primeCand);
  7.  
  8. static int count = 0;
  9. pthread_mutex_t sem;
  10. void decrement_count(){
  11. pthread_mutex_lock(&sem);
  12. count--;
  13. pthread_mutex_unlock(&sem);
  14. }
  15. int threadCount(){
  16. int res = 0;
  17. pthread_mutex_lock(&sem);
  18. res = count;
  19. pthread_mutex_unlock(&sem);
  20. return res;
  21. }
  22. void incrementCount(){
  23. pthread_mutex_lock(&sem);
  24. count++;
  25. pthread_mutex_unlock(&sem);
  26. }
  27. void initProcess(void* n){
  28. char good = 1;
  29. while(good){
  30. if(threadCount() < 20) {
  31. pthread_t pthread;
  32. incrementCount();
  33. pthread_create(&pthread, NULL, isPrime, n);
  34. //pthread_detach(pthread);
  35. //pthread_join(pthread, NULL);
  36. good = 0;
  37. }
  38. else{
  39. good = 1;
  40. }
  41. }
  42.  
  43. }
  44. void* isPrime(void* n){
  45. long primeCand = (long)n;
  46. if(primeCand == 0 or primeCand == 1)
  47. return NULL;
  48. int i = 2;
  49. while(i <= primeCand){
  50. if(primeCand%i == 0)
  51. break;
  52. i++;
  53. }
  54. if( i == primeCand)
  55. printf("%li ",primeCand);
  56. decrement_count();
  57. }
  58. int main() {
  59. long n = 0;
  60. pthread_mutex_init(&sem,0);
  61. scanf("%li",&n);
  62. long k = 0;
  63. while(k <= n){
  64. initProcess((void*)k);
  65. k++;
  66. }
  67. sleep(1);
  68. pthread_mutex_destroy(&sem);
  69. return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement