C语言 使用 pthread 未打印预期值



我创建了以下程序:

void *thread(void *vargp) {
int *ptr = (int*)vargp;
printf("vargp = %p, *vargp = %dn",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 = %pn", i, &i);
pthread_create(&tid2, NULL, thread2, (void*)&i);
pthread_join(tid, (void**)&i);
pthread_join(tid2, NULL);
printf("at the end i = %dn",i);
}

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

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

由于 vargp 获得的地址与变量 i 相同,为什么 *vargp 没有打印出值 42,而是打印出值 0?

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

您的程序表现出数据争用(一种未定义行为的形式(:其结果取决于thread还是thread2首先运行,并且无法保证该顺序。在多处理器机器(目前最常见的(上,两个线程可以同时运行。

如果要保证thread将在thread2之前运行,则需要等待它(通过pthread_join(才能创建thread2

最新更新