The
start_routine( ) function
in the
pthread_create( ) call
was defined as:
void * (*start_routine) ( void * )
^^^^^^ ^^^^^^
return type parameter type
I.e.: the
start_routine( ) function
has the
followingform:
void * functionName( void *arg )
{
....
}
The data typevoid * is a
"general purpose" pointertype
Defining a
start_routine
with a
argument
The start_routine( ) function
of a thread can have
an arbitrarypointer typeparameter
Example: a
start_routine( ) functionnamedworker( )
with an int *parameter:
void *worker(void *arg)
{
int *p; // Pointer (reference, address) to an integer variable
int x; // An integer variable
p = (int *) arg; // Cast "(void *)" type to "(int *)"
x = *p // Retrieve the int value in arg
printf("arg = %d\n", x);
return(NULL); // Thread exits
}
Note:
Technically, we are
retrieving
the integer value from
*arglike this:
int x = *arg; // But this syntax is illegal
// because arg's data type is void * (unknown)
// We need to cast to an int * first !
Passing an
pointer argumenet to
the start_routine( ) of
a thread
You can pass
the
address of
a variable of
any data type
as an argument to the
start_routine( ) of
a thread
Example: pass the
address of an
int variable to
the start_routine( ) of
a thread
int main(int argc, char *argv[])
{
pthread_t tid;
int param; // Integer
param = 12345; // Initialize param var
pthread_create(&tid, NULL, worker, ¶m);
sleep(1);
}
When the
worker( ) function is
executed by the
new thread, the
arg of the
worker( ) function
will contain the
value 12345