The following is an example program from the book Computer Systems: A Programmer's Perspective where the authors illustrate the usage of shared variables in multi-threaded programs:
#include "csapp.h"
#define N 2
void *thread(void *vargp);
char **ptr; /* Global variable */
int main()
{
int i;
pthread_t tid;
char *msgs[N] = {
"Hello from foo",
"Hello from bar"
};
ptr = msgs;
for (i = 0; i < N; i++)
Pthread_create(&tid, NULL, thread, (void *)i);
Pthread_exit(NULL);
}
void *thread(void *vargp)
{
int myid = (int)vargp;
static int cnt = 0;
printf("[%d]: %s (cnt=%d)\n", myid, ptr[myid], ++cnt);
return NULL;
}
As can be seen, both threads access the global variable ptr which points to the local variable msgs of the main thread which calls pthread_exit.
Now, according to the documentation of pthread_exit:
After a thread has terminated, the result of access to local (auto) variables of the thread is undefined.
So, is the code above correct?
Is it legal to access a local variable of the main thread from another thread even though the main thread calls pthread_exit?