Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <stdlib.h>
- #include <string.h>
- void *thread_timer(void *timer);
- int thread_attivo = 0, timer;
- int main()
- {
- char scelta[12];
- int res;
- pthread_t t_id;
- printf("\t\tBenvenuto nel programma sui Thread!\n");
- while(1)
- {
- printf("\nDigita un comando: ");
- scanf("%s", scelta);
- if(!strcmp(scelta, "start"))
- {
- if(thread_attivo)
- {
- printf("Il thread è già attivo..\n");
- continue;
- }
- thread_attivo = 1;
- printf("Digita il numero di secondi del timer: ");
- scanf("%d", &timer);
- res = pthread_create(&t_id, NULL, thread_timer, (void *)timer);
- if(res != 0)
- {
- printf("Si è verificato un errore nella creazione del thread figlio.\n");
- continue;
- }
- sleep(0.1);
- }
- else if(!strcmp(scelta, "stop"))
- {
- if(thread_attivo == 0)
- {
- printf("Il thread non è attivo..\n");
- continue;
- }
- res = pthread_cancel(t_id);
- if(res != 0)
- {
- printf("Errore nella cancellazione del thread figlio.\n");
- continue;
- }
- pthread_join(t_id, NULL);
- thread_attivo = 0;
- printf("Il thread figlio è stato cancellato.\n");
- }
- else if(!strcmp(scelta, "quit"))
- {
- if(thread_attivo)
- {
- res = pthread_cancel(t_id);
- if(res != 0)
- {
- printf("Errore nella cancellazione del thread figlio.\n");
- printf("Chiusura programma in corso..\n");
- sleep(2);
- exit(EXIT_FAILURE);
- }
- pthread_join(t_id, NULL);
- printf("Il thread figlio è stato cancellato.\n");
- }
- printf("Chiusura programma in corso..\n");
- sleep(2);
- exit(EXIT_SUCCESS);
- }
- else
- {
- printf("Comando non valido!\n");
- continue;
- }
- }
- }
- void *thread_timer(void *timer)
- {
- printf("Salve, sono il thread figlio e devo attendere %d secondi\n", (int)timer);
- sleep((int)timer);
- thread_attivo = 0;
- // printf("Thread disattivato.\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement