In multithreaded programming. It is often necessary to pass the parameters from the main thread to the child thread or to get the calculation results of the child threads in the main thread.
If you use global variables to implement. Must protect the critical area, resulting in a large number of switching work resulting in inefficient.
and the use of inter-process parameter transfer can solve this problem.
Two-direction parameter transfer:
1. Main Line Cheng thread pass the number of parameters:
by function int Pthread_create (pthread_t *thread, const pthread_attr_t *attr,void * (*start_routine) (void *), void *arg);
When the thread is created. Use the parameter arg to pass the parameters to the child thread.
2. The child thread passes the number of references to the main thread:
Through the function int pthread_join (pthread_t thread, void **retval);
The main thread waits for the child thread to end and reads the return value of the retval from the number of parameters.
When multiple simple structure parameters need to be passed, the number of passes between threads is usually defined as a struct.
The following is a simple example:
#include <stdio.h> #include <stdlib.h>typedef struct data//The parameter structure passed between threads { long *a; Long *b;} Data;void *thread_handle (void *args)//thread handler function { Data *rev = (data *) args; Data *ret = (data *) malloc (sizeof (data)); Ret->a = (long *) malloc (sizeof (long)); Ret->b = (long *) malloc (sizeof (long)); * (RET->A) = 2 * (* (rev->a)); * (RET->B) = 2 * (* (rev->b)); return (void *) ret; int main () { pthread_t pid; void *ret; Data *tmp = (data *) malloc (sizeof (data)); Tmp->a = (long *) malloc (sizeof (long)); Tmp->b = (long *) malloc (sizeof (long)); * (tmp->a) = 5; * (tmp->b) = 6; Pthread_create (&pid, NULL, Thread_handle, (void *) TMP); Pthread_join (PID, &ret); printf ("a=%ld\n", * ((data *) ret)->a)); printf ("b=%ld\n", * ((data *) ret)->b));
The above program uses a sub-thread to pass the main thread to the parameters of each of the 2 returned, the main thread receives the returned results and outputs
If the source file is test.c. Run
GCC Test.c-lpthread
./a.out
'll be
Parameter passing between threads