Reputation: 11351
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
Upvotes: 1
Views: 1085
Reputation: 60037
The bad case returns a pointer to a bit of the stack - like a bird that has flown out of the window long time ago!
But if it works - you are going to have a very very random number - a bit better that sallting the random number gerenrator with the id of the thread!
Upvotes: 0
Reputation: 36059
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.
Upvotes: 5
Reputation: 11906
In the bad case, your return &num, where num is a local variable on the stack, which is only valid during the function scope. Once you return, it is no longer valid.
Upvotes: 1