开发者

Return Value of a pthread_create

I am attempting to make the following call,

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

schedule_sync returns a value, I would like to be able to grab that value, but from what Ive read about pthread_create, you should pass a "void" function. Is it possible to get the 开发者_开发技巧return value of schedule_sync, or am I going to have to modify some kind of parameter passed in?

Thanks for the help!


pthread_create returns an <errno.h> code. It doesn't create a new process so there's no new PID.

To pass a pointer to your function, take its address with &.

pthread_create takes a function of form void *func( void * ).

So assuming schedule_sync is the thread function,

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;
}


In order to catch the return value of child thread in parent(read as main) thread.

You have to :

1) Joint the child threads with main thread. So that main thread stays and waits for the child threads to do their stuff and exit.

2) Catch the return value of child thread while exiting. Child thread shall call pthread_exit(&ret_val), where ret_val holds the exit value of the function(child thread was executing)

Info:

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

void pthread_exit(void *rval_ptr);

Explanation:

*Main Function:*

After pthread_create, join child thread:

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

Child Thread Processing Function:

  ret_val_of_child_thread = 10;

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

Main Function: After Child Thread is done executing, one can catch its return value in main thread from "*(valid typecast *) *p_ret_val_of_child_thread"

The second argument of pthread_join holds the return value of child thread function handler exit value.


schedule_sync should return void* which can be anything. You can grab the value with 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);

When thread terminates

pthread_joint(&t, locationToPutReturnValue);

Don't have a development enviroment, so I can't get you the exact sequence just yet, but this will hopefully get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜