Advertisement
Guest User

Untitled

a guest
Nov 24th, 2016
135
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. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. void *thread_timer(void *timer);
  8.  
  9. int thread_attivo = 0, timer;
  10.  
  11. int main()
  12. {
  13.   char scelta[12];
  14.   int res;
  15.   pthread_t t_id;
  16.   printf("\t\tBenvenuto nel programma sui Thread!\n");
  17.   while(1)
  18.     {
  19.       printf("\nDigita un comando: ");
  20.       scanf("%s", scelta);
  21.       if(!strcmp(scelta, "start"))
  22.     {
  23.       if(thread_attivo)
  24.         {
  25.           printf("Il thread è già attivo..\n");
  26.           continue;
  27.         }
  28.       thread_attivo = 1;
  29.       printf("Digita il numero di secondi del timer: ");
  30.       scanf("%d", &timer);
  31.       res = pthread_create(&t_id, NULL, thread_timer, (void *)timer);
  32.       if(res != 0)
  33.         {
  34.           printf("Si è verificato un errore nella creazione del thread figlio.\n");
  35.           continue;
  36.         }
  37.       sleep(0.1);
  38.     }
  39.       else if(!strcmp(scelta, "stop"))
  40.     {
  41.       if(thread_attivo == 0)
  42.         {
  43.           printf("Il thread non è attivo..\n");
  44.           continue;
  45.         }
  46.       res = pthread_cancel(t_id);
  47.       if(res != 0)
  48.         {
  49.           printf("Errore nella cancellazione del thread figlio.\n");
  50.           continue;
  51.         }
  52.       pthread_join(t_id, NULL);
  53.       thread_attivo = 0;
  54.       printf("Il thread figlio è stato cancellato.\n");
  55.     }
  56.       else if(!strcmp(scelta, "quit"))
  57.     {
  58.       if(thread_attivo)
  59.         {
  60.           res = pthread_cancel(t_id);
  61.           if(res != 0)
  62.         {
  63.           printf("Errore nella cancellazione del thread figlio.\n");
  64.           printf("Chiusura programma in corso..\n");
  65.           sleep(2);
  66.           exit(EXIT_FAILURE);
  67.         }
  68.           pthread_join(t_id, NULL);
  69.           printf("Il thread figlio è stato cancellato.\n");
  70.         }
  71.       printf("Chiusura programma in corso..\n");
  72.       sleep(2);
  73.       exit(EXIT_SUCCESS);
  74.     }
  75.       else
  76.     {
  77.       printf("Comando non valido!\n");
  78.       continue;
  79.     }
  80.     }
  81. }
  82.  
  83. void *thread_timer(void *timer)
  84. {
  85.   printf("Salve, sono il thread figlio e devo attendere %d secondi\n", (int)timer);
  86.   sleep((int)timer);
  87.   thread_attivo = 0;
  88.   // printf("Thread disattivato.\n");
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement