返回pthread_create的值

时间:2010-08-27 02:44:52

标签: c pthreads

我正在尝试拨打以下电话,

PID = pthread_create(&t, NULL, schedule_sync(sch,t1), NULL);

schedule_sync返回一个值,我希望能够获取该值,但是从我读过的关于pthread_create的内容中,你应该传递一个“void”函数。是否有可能获得schedule_sync的返回值,或者我将不得不修改传入的某种参数?

感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

pthread_create会返回<errno.h>代码。它不会创建新进程,因此没有新的PID。

要传递指向您的函数的指针,请使用&的地址。

pthread_create采用void *func( void * )形式的函数。

所以假设schedule_sync是线程函数,

struct schedule_sync_params {
    foo sch;
    bar t1;
    int result;
    pthread_t thread;
} args = { sch, t1 };

int err = pthread_create( &args.thread, NULL, &schedule_sync, &args );
 .....

schedule_sync_params *params_ptr; // not necessary if you still have the struct
err = pthread_join( args.thread, &params_ptr ); // just pass NULL instead
 .....

void *schedule_sync( void *args_v ) {
   shedule_sync_params *args = args_v;
   ....
   args->result = return_value;
   return args;
}

答案 1 :(得分:2)

为了捕获父线程中的子线程的返回值(作为主线程读取)。

您必须:

1)将子线程与主线程联系起来。因此,主线程保持并等待子线程执行其操作并退出。

2)退出时捕获子线程的返回值。子线程应调用pthread_exit(&amp; ret_val),其中ret_val保存函数的退出值(子线程正在执行)

<强>的信息:

int pthread_join(pthread_t thread, void **rval_ptr);

void pthread_exit(void *rval_ptr);

<强>解释

* 主要功能: *

在pthread_create之后,加入子线程:

pthread_join(thread_id, (void**)&(p_ret_val_of_child_thread));

子线程处理函数:

  ret_val_of_child_thread = 10;

  pthread_exit(&ret_val_of_child_thread);
  } /* Child Thread Function Handler Ends */

主要功能:   在子线程完成执行后,可以从“*(有效的类型转换*)* p_ret_val_of_child_thread”

中捕获主线程中的返回值

pthread_join的第二个参数保存子线程函数处理程序退出值的返回值。

答案 2 :(得分:1)

schedule_sync应返回void *,可以是任何内容。您可以使用pthread_join获取值。

//Function shoulde be look like this
void* schedule_sync(void* someStructureWithArguments);

//Call pthread_create like so
pthread_create(&t, NULL, schedule_sync, locationOfSomeStructureWithArguments);

线程终止时

pthread_joint(&t, locationToPutReturnValue);

没有开发环境,所以我还不能确切地说明你的确切顺序,但这有望让你开始。