Advertisement
Guest User

Untitled

a guest
Nov 27th, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <pthread.h>
  4.  
  5. #define MAX 20
  6. #define THREAD_MAIN 0
  7. #define THREAD_CONTROLLER 1
  8.  
  9. int count = 0;
  10. pthread_mutex_t mutex;
  11. int scheduler;
  12.  
  13. void *controlling(void *arg);
  14. int numero_primo(int num);
  15.  
  16. int main()
  17. {
  18.   printf("Benvenuto nel programma.\n");
  19.   pthread_t controller;
  20.   pthread_mutex_init(&mutex, NULL);
  21.   pthread_create(&controller, NULL, &controlling, NULL);
  22.   while(count < MAX)
  23.     {
  24.       if(scheduler == THREAD_MAIN)
  25.     {
  26.       pthread_mutex_lock(&mutex);
  27.       count ++;
  28.       pthread_mutex_unlock(&mutex);
  29.       scheduler = THREAD_CONTROLLER;
  30.     }    
  31.     }
  32. }
  33.  
  34. void *controlling(void *arg)
  35. {
  36.   while(count <= MAX)
  37.     {
  38.       if(scheduler == THREAD_CONTROLLER)
  39.     {
  40.       pthread_mutex_lock(&mutex);
  41.       if(numero_primo(count))
  42.         {
  43.           printf("%d\n", count);
  44.           fflush(stdout);
  45.         }
  46.       pthread_mutex_unlock(&mutex);
  47.       scheduler = THREAD_MAIN;
  48.     }
  49.     }
  50. }
  51.  
  52. int numero_primo(int num)
  53. {
  54.   for(int i = 2; i < num; i++)
  55.       if( (num % i) == 0)
  56.     return 0;
  57.   return 1;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement