【问题标题】:pthread_exit issues returning structpthread_exit 问题返回结构
【发布时间】:2012-10-14 22:33:19
【问题描述】:

我有一个结构

typedef struct something_t {
    int a;
    int b;
} VALUES;

在我的线程函数中我做

VALUES values;
values.a = 10;
values.b = 11;

pthread_exit((void*)&values);

我尝试通过做来接收

VALUES values;
pthread_join(thread, (void*)&values);
printf("A: %d\B: %d\n", values.a, values.b);

我收到的值每次都很奇怪。 我对如何接收我最终在线程中创建的值感到困惑。我正在尝试学习 C 中的线程,似乎我已经掌握了它,但我无法返回值。有办法吗?感谢任何人的帮助。

【问题讨论】:

    标签: c multithreading pthreads pthread-join


    【解决方案1】:

    您正在尝试返回堆栈(本地)变量。

    这是不允许的,也不会起作用,因为线程的堆栈会在线程退出时被删除(或至少是无效的)。

    解决这个问题:

    VALUES *values = malloc(sizeof VALUES);
    values->a = 1;
    values->b = 2;
    pthread_exit( values );
    

    然后,当你加入时,这些值是免费的

    VALUES *res;
    pthread_join( thread, &res );
    ...
    free(res);
    

    【讨论】:

    • 太棒了!非常感谢,我没有意识到堆栈会在每个新线程结束时被转储,但我确实注意到除了每个线程中的全局变量之外的所有内容都分配了新内存。
    【解决方案2】:

    看起来你正在线程函数上创建一个堆栈对象并在pthread_exit 中使用它。当线程函数退出时,该结构超出范围,您将留下垃圾。

    您没有使用传递给pthread_join 的值结构。

    【讨论】:

      【解决方案3】:

      您的应用程序具有未定义的行为,因为您在堆栈(以及已退出线程的堆栈)上声明了结构

      改用malloc

      VALUES *values = malloc(sizeof(VALUES);
      values->a = 10;
      values->b = 11;
      
      pthread_exit(values);
      

      【讨论】:

        【解决方案4】:

        添加到perh's answer:在必要时使用指针类型转换。

        线程函数:

        VALUES *values = (VALUES*) malloc(sizeof VALUES);
        values->a = 1;
        values->b = 2;
        pthread_exit( (void*)values );
        

        调用函数:

        VALUES *res;
        pthread_join( thread_id, (void*)&res );
        ...
        free(res);
        

        这是安全的,它不会在编译时产生警告。

        【讨论】:

          猜你喜欢
          • 2012-06-11
          • 2011-04-20
          • 1970-01-01
          • 2017-07-21
          • 2019-10-05
          • 2013-12-04
          • 1970-01-01
          • 2011-09-18
          • 1970-01-01
          相关资源
          最近更新 更多