c - 使用 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?
解决方案
既然 vargp 得到了与变量 i 相同的地址,为什么 *vargp 没有打印出值 42,而是值 0?
您的程序表现出数据竞争(一种未定义的行为):其结果取决于是否thread
先thread2
运行,并且不能保证该顺序。在多处理器机器上(现在最常见),两个线程可以同时运行。
如果你想保证它thread
会在之前运行thread2
,你需要在创建之前等待它(通过pthread_join
)。thread2
推荐阅读
- javascript - 如何从 .txt 文件中读取数据并将数据转换为整数?
- python - 在 Python 中对单个数组进行更快的双重迭代
- c# - WPF - 避免在 RichTexBox 上的文件加载时触发 TextChanged 事件
- python - 如何使用 PySNMP 指定 auth/priv 密钥而不是密码短语?
- ruby-on-rails - 如何为acts_as_votable嵌套资源编写link_to?
- scala - 如何有条件地向呼叫添加资源
- powershell - Powershell 使用另一个变量引用更新变量
- jquery - 如何从jQuery中的侦听器函数获取事件调用者
- python-3.x - 使用 Python 向子字符串添加值的建议
- javascript - svg 文件中的 JavaScript 上下文