从下面的代码中,输出答案只是8
?还有什么其他可能的输出(解释会很棒)?
int i = 0;
void *doit(void *vargp) {
i = i + 5;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, doit, NULL);
i = i + 3;
pthread_join(tid, NULL);
printf("%d\n", i);
}
答案 0 :(得分:1)
由于您不使用互斥锁,因此您可能遇到未定义的行为,其中主线程和doit线程都看到i = 0然后i设置为5或3.
修复可能是:
int i = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // this is since the mutex is a global variable.
void *doit(void *vargp) {
pthread_mutex_lock(mutex);
i = i + 5;
pthread_mutex_unlock(mutex);
}
int main() {
pthread_t tid;
int *ptr = &i;
pthread_create(&tid, NULL, doit, NULL);
pthread_mutex_lock(mutex);
i = i + 3;
pthread_mutex_unlock(mutex);
pthread_join(tid, NULL);
printf("%d",i);
}