首页 > 解决方案 > 使用 pthread 未打印预期值

问题描述

我创建了以下程序:

void *thread(void *vargp) {
  int *ptr = (int*)vargp;
  printf("vargp = %p, *vargp = %d\n",vargp, *(int*)vargp);
  pthread_exit((void*)*ptr);
}

void *thread2(void *vargp) {
  int *ptr = (int*)vargp;
  *ptr = 0;
  pthread_exit((void*)31);
}

int main(){
  int i = 42;
  pthread_t tid, tid2;
  pthread_create(&tid, NULL, thread, (void*)&i);
  printf("i = %d, &i = %p\n", i, &i);
  pthread_create(&tid2, NULL, thread2, (void*)&i);
  pthread_join(tid, (void**)&i);
  pthread_join(tid2, NULL);
  printf("at the end i = %d\n",i);
}

我希望主函数中的最后一个 printf 打印“最后 i = 42”。但是,它会打印以下内容:

i = 42, &i = 0x7ffcf3b65c4c
vargp = 0x7ffcf3b65c4c, *vargp = 0
0

既然 vargp 得到了与变量 i 相同的地址,为什么 *vargp 没有打印出值 42,而是值 0?

标签: clinuxpthreads

解决方案


既然 vargp 得到了与变量 i 相同的地址,为什么 *vargp 没有打印出值 42,而是值 0?

您的程序表现出数据竞争(一种未定义的行为):其结果取决于是否threadthread2运行,并且不能保证该顺序。在多处理器机器上(现在最常见),两个线程可以同时运行。

如果你想保证它thread会在之前运行thread2,你需要在创建之前等待它(通过pthread_join)。thread2


推荐阅读