/* - Creation of the threads with pthread_create() - Exchange with the threads of a structure with different values for each thread - Exchange with the main of the returned value of a thread - Wait a thread with pthread_join() - Global variables and threads */ #include #include #include #include #define N_THREAD 3 /* Global variable, all the threads can see this variable, if a thread modify the value of the variable, all the other threads see the modified value. Important: variables cannot be modified by more than one thread at a time, otherwise a race condition is generated. */ 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->thread_num == 0) global_variable = 20; fprintf (stdout, "Starting thread %d, letter=%c, global_variable=%d\n", param->thread_num, param->letter, global_variable); for (i = 0; i < 10; i++) write (STDOUT_FILENO, &(param->letter), 1); /* By default, when a process is executed the file descriptors number 0, 1 and 2 are automatically opened, and assigned to stdin, stdout and stderr, respectivelly */ printf("\n"); param->letter = toupper(param->letter); pthread_exit(&(param->letter)); } int main (void) { int retcode; pthread_t th[N_THREAD]; char *retval; my_t value[N_THREAD]; int i = 0; for(i=0; i