【问题标题】:Different possible program outputs?不同的可能程序输出?
【发布时间】:2017-05-10 15:34:14
【问题描述】:

从下面的代码中,输出答案是否只有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);
}

【问题讨论】:

  • 你测试了吗?
  • 由于您的程序具有从多个线程对对象的非只读、非原子、非同步访问,因此行为未定义。因此,该程序完全没有意义。程序不需要任何输出,如果有,输出是“大象”是完全允许的。
  • @EOF 这是练习题之一。根据给定的代码,可能的输出是 3 还是 8 ?
  • @ssss 那么你的导师不知道 C。可能的输出范围不受限制。

标签: c pthreads


【解决方案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);
}

【讨论】:

  • 所以从原始问题来看,答案可能是 3,5 和 8 ?
  • @ssss:这是最低限度的答案——也可能有各种形式的垃圾,具体取决于...
猜你喜欢
  • 2023-02-22
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 2015-04-28
  • 2017-03-16
相关资源
最近更新 更多