【问题标题】:Why does start_routine for pthread_create return void* and take void*为什么 pthread_create 的 start_routine 返回 void* 并取 void*
【发布时间】:2010-11-24 01:23:00
【问题描述】:

pthread_create 的函数头如下所示:

int pthread_create(pthread_t * thread, 
                   const pthread_attr_t * attr,
                   void * (*start_routine)(void *), 
                   void *arg);

除了start_routine 的函数指针是void* (*fpointer) (void*) 的形式,这意味着它接受void* 并返回void*,我完全理解。

void* 参数只是将参数传递给start_routine 的一种方式,我明白了那部分,但我不明白为什么函数返回void*?什么代码甚至会注意到该返回值?

【问题讨论】:

    标签: c posix pthreads


    【解决方案1】:

    来自pthread_create 的文档:

    线程是在执行start_routine 时创建的,arg 作为其唯一参数。如果start_routine 返回,效果就像使用start_routine 的返回值作为退出状态隐式调用pthread_exit()。请注意,最初调用 main() 的线程与此不同。当它从main() 返回时,效果就像隐式调用exit(),使用main() 的返回值作为退出状态。

    还有pthread_exit:

    pthread_exit() 函数终止调用线程并使值value_ptr 可用于任何成功的join 与终止线程。

    因此,如果您在线程上执行pthread_join,则它返回的指针将传递回加入线程,从而允许您将信息从垂死的线程传输到另一个活跃的线程。

    【讨论】:

      【解决方案2】:

      来自spec

      如果start_routine 返回,则 效果好像有一个隐含的 调用pthread_exit() 使用 start_routine 的返回值作为 退出状态。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-08
        • 2011-12-17
        • 2011-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-29
        相关资源
        最近更新 更多