【发布时间】:2011-12-14 18:37:20
【问题描述】:
我正在对教授的讲义进行复习。当我到达并发部分时,我得到了这个问题:
在幻灯片中,教授给出了两个使用 pthread 的例子(一个是好例子,一个是坏例子)。但我不明白为什么它们之间存在差异。
这是一个很好的例子:
#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;
}
糟糕的例子是
#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;
}
谁能理解这两个例子,请给我解释一下为什么坏的和第一个不一样,为什么不好?
谢谢
艾伦
【问题讨论】:
标签: c multithreading concurrency pthreads