Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Value of a pthread_create

Tags:

c

pthreads

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!

like image 379
onaclov2000 Avatar asked Aug 27 '10 02:08

onaclov2000


People also ask

What does pthread_create return when successful?

Returned value If successful, pthread_create() returns 0.

How do I get my Pthread return value?

If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.

How do you return a value from a thread?

How to Return Values From a Thread. A thread cannot return values directly. The start() method on a thread calls the run() method of the thread that executes our code in a new thread of execution. The run() method in turn may call a target function, if configured.

What are the parameters of pthread_create?

PARAMETERS. Is the location where the ID of the newly created thread should be stored, or NULL if the thread ID is not required. Is the thread attribute object specifying the attributes for the thread that is being created. If attr is NULL, the thread is created with default attributes.


1 Answers

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;
}
like image 96
Potatoswatter Avatar answered Oct 22 '22 20:10

Potatoswatter