hi all,

i want to execute a function by a separate thread and get that functions return value in to the main thread.

one way to do this is set a global variable by that separate thread and access that variable from the main thread. This procedure is as follow.

int tid = 0; // global variable

void *PrintHello(void *threadid)

{

tid = (int)threadid;
// set the global variable by a separate thread
}


int main (int argc, char *argv[])

{

pthread_t threads[NUM_THREADS];

int rc, t;

for(t=0; t<NUM_THREADS; t++){

rc = pthread_create(&threads[t],NULL,PrintHello,(void *)t);

}

printf(“thread id is %d”, tid); //access the global variable from the main thread
}

is there any other way to do this...? because i want to assurance that this value is just returned from the execution of this separate thread not an old value. that is if the PrintHello function get some times to finalize its execution, the printed value may be the old value. so i want to avoid this.

Look up pthread_exit() and pthread_join() for ways of communicating information from the thread back to the parent.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.