【问题标题】:Function of retval in pthread_joinpthread_join 中的 retval 函数
【发布时间】:2020-06-12 18:43:57
【问题描述】:

我正在学习操作系统中的 C 线程。我不知道为什么下面的代码给了我分段错误。有人能帮我一下吗?我也对pthread_join 如何使用它的论点void ** retval 感到有些困惑。它的作用是什么?

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 

void *thread (void *vargp) {
   int* arg = *((int*)vargp);
   return (void*)arg;
}   

int main () {
   pthread_t tid;
   int thread_arg = 0xDEADBEEF;
   int *ret_value;
   pthread_create(&tid, NULL, thread, &thread_arg);
   pthread_join(tid, (void **)(&ret_value));
   printf("%X\n", *ret_value);
   return 0; 
}

【问题讨论】:

  • 线程应该调用pthread_exit()来传递返回值。
  • @Barmar 也可以从线程函数中返回。
  • ...毕竟,这就是为什么线程函数所需的签名声明它返回void *

标签: c operating-system pthreads


【解决方案1】:

这是不正确的:

int* arg = *((int*)vargp);  

(int*)vargp 将您的 void* 转换为 int*。但是通过写入int* arg = *((int*)vargp);,您将参数vargp 的值(0xDEADBEEF)赋值给arg 指针。此值 (0xDEADBEEF) 不是有效地址。
你的编译器是什么版本?因为他必须提醒你:

intint* 的转换无效

你应该写:

int* arg = (int*) vargp;

【讨论】:

  • 另外,这是UB:pthread_join(tid, (void **)(&amp;ret_value));ret_value 需要有void * 类型,然后你只需传递&amp;ret_value。在pthread_join 返回后,您可以将ret_value 转换为int * 或通过赋值/强制转换/其他任何适当的指针类型。
猜你喜欢
  • 2016-09-17
  • 2021-10-15
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2020-10-30
  • 1970-01-01
相关资源
最近更新 更多