I am doing a review with my professor’s lecture note. I got this question when I reached the concurrency section:
in the slide, professor gave two examples of using pthread (one is good example and the other is bad.). But I dont understand why there is a difference between them.
here is the good example:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *get_rand_num(void *args) {
int *nump = malloc(sizeof(int));
srand(pthread_self());
*nump = rand();
return nump;
}
int main() {
pthread_t tid;
void *ptr = NULL;
pthread_create(&tid, NULL, get_rand_num, NULL);
pthread_join(tid, &ptr);
printf("Random number: %d\n", * (int *) ptr);
return 0;
}
And the bad example is
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *get_rand_num(void *args) {
int num;
srand(pthread_self());
num = rand();
return #
}
int main() {
pthread_t tid;
void *ptr = NULL;
pthread_create(&tid, NULL, get_rand_num, NULL);
pthread_join(tid, &ptr);
printf("Random number: %d\n", * (int *) ptr);
return 0;
}
Anyone can understand these two examples please explain to me why the bad one is different from the first one, and why it is not good?
Thank you
allan
The bad example returns a pointer to a local variable. This is always a bad idea, because local variables die when the function returns. This is no problem specific to multi-threaded programs, but aggravated because threads get one stack per thread, which is deallocated after the
pthread_join. While you often get lucky in single-threaded programming and can use the pointer immediately after the function’s return, the whole segment containing the old thread’s stack might have gone back to the operating system in the bad example and accesses would produce segmentation faults.The first example is also not very good since it produces a memory leak.