This shows you the differences between two versions of the page.
it:informatica:posix:threads_esempio1 [2017/11/30 06:59] |
it:informatica:posix:threads_esempio1 [2020/11/26 23:18] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Threads Esempio 1 ====== | ||
+ | **Concetti: | ||
+ | Esempio riguardante le funzionalità principali dei thread POSIX | ||
+ | **Testo: | ||
+ | Realizzare un programma di esempio di utilizzo delle funzionalità dei thread | ||
+ | |||
+ | **Soluzione: | ||
+ | <file C threads_esempio1.c> | ||
+ | /* | ||
+ | - Creazione di thread con pthread_create | ||
+ | - Passaggio ai thread di una struttura con valori diversi per ogni thread | ||
+ | - Passaggio di un valore di ritorno tra i thread e il main | ||
+ | - Attesa di thread con pthread_join | ||
+ | */ | ||
+ | |||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | #define N_THREAD 3 | ||
+ | |||
+ | |||
+ | /* Variabile globale, tutti i thread vedono questo valore, se un thread ne modifica il valore anche gli altri thread lo vedono modificato */ | ||
+ | int global_variable = 10; | ||
+ | |||
+ | |||
+ | typedef struct { | ||
+ | int thread_num; | ||
+ | char letter; | ||
+ | } my_t; | ||
+ | |||
+ | |||
+ | static void *process (void *arg) | ||
+ | { | ||
+ | int i; | ||
+ | my_t *param = (my_t *) arg; // cast the void argument to the real type | ||
+ | |||
+ | if (param-> | ||
+ | fprintf (stdout, " | ||
+ | for (i = 0; i < 10; i++) | ||
+ | write (STDOUT_FILENO, | ||
+ | printf(" | ||
+ | param-> | ||
+ | pthread_exit(& | ||
+ | } | ||
+ | |||
+ | |||
+ | int main (void) | ||
+ | { | ||
+ | int retcode; | ||
+ | pthread_t th[N_THREAD]; | ||
+ | char *retval; | ||
+ | my_t value[N_THREAD]; | ||
+ | int i = 0; | ||
+ | | ||
+ | for(i=0; i< | ||
+ | value[i].letter = ' | ||
+ | } | ||
+ | |||
+ | for(i=0; i< | ||
+ | value[i].thread_num = i; | ||
+ | retcode = pthread_create (& | ||
+ | if (retcode != 0) | ||
+ | fprintf (stderr, " | ||
+ | } | ||
+ | |||
+ | |||
+ | for(i=0; i< | ||
+ | |||
+ | retcode = pthread_join (th[i], (void *)& | ||
+ | if (retcode != 0) | ||
+ | fprintf (stderr, " | ||
+ | |||
+ | fprintf(stdout, | ||
+ | } | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | **Commenti: |