I wrote a simple task like the following. It prints a string, increments the global variable glob, and returns its value, through the pthread_exit, to the pthread_join.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
int glob = 0;
void *task()
{
printf("I am a simple thread.\n");
glob++;
pthread_exit((void*)&glob);
}
int main()
{
pthread_t tid;
int create = 1;
void **ppvglob;
create = pthread_create(&tid, NULL, task, NULL);
if (create != 0) exit(EXIT_FAILURE);
pthread_join(tid, ppvglob);
int **ppv = (int**)ppvglob;
printf("Variabile globale restituita alla terminazione del thread: %d\n", **ppv);
return(0);
}
The compiler gives me the error:
main.c: In function ‘main’:
main.c:29:2: warning: ‘ppvglob’ may be used uninitialized in this function [-Wmaybe-uninitialized]
29 | pthread_join(tid, ppvglob);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
Could you tell me the reason please?
When doing:
pthread_join(tid, ppvglob);
because you never initialized ppvglob it is normal the compiler protest, but in fact you must replace:
void **ppvglob; .... pthread_join(tid, ppvglob);
by:
void *pvglob; .... pthread_join(tid, &pvglob);
then of course:
int **ppv = (int**)ppvglob; printf("Variabile globale restituita alla terminazione del thread: %d\n", **ppv);
by:
int *pv = (int*)pvglob; printf("Variabile globale restituita alla terminazione del thread: %d\n", *pv);
So having:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
int glob = 0;
void *task()
{
printf("I am a simple thread.\n");
glob++;
pthread_exit((void*)&glob);
}
int main()
{
pthread_t tid;
int create = 1;
void *pvglob;
create = pthread_create(&tid, NULL, task, NULL);
if (create != 0) exit(EXIT_FAILURE);
pthread_join(tid, &pvglob);
int *pv = (int*)pvglob;
printf("Variabile globale restituita alla terminazione del thread: %d\n", *pv);
return(0);
}
Compilation and execution:
% gcc -Wall c.c -lpthread
% ./a.out
I am a simple thread.
Variabile globale restituita alla terminazione del thread: 1
that print 1 because this is the value of glob