mahmood mahmood - 1 month ago 6
C Question

number of arguments for a function in pthread

In hello world example of pthread it is stated:

#include <pthread.h>
#include <stdio.h>

void * print_hello(void *arg)
{
printf("Hello world!\n");
return NULL;
}

int main(int argc, char **argv)
{
pthread_t thr;
if(pthread_create(&thr, NULL, &print_hello, NULL))
{
printf("Could not create thread\n");
return -1;
}

if(pthread_join(thr, NULL))
{
printf("Could not join thread\n");
return -1;
}
return 0;
}


As you can see
print_hello
in
pthread_create()
has no argument, however in the definition, it looks like
void * print_hello(void *arg)


What does that mean?

Now assume I have this implementation

void * print_hello(int a, void *);
int main(int argc, char **argv)
{
pthread_t thr;
int a = 10;
if(pthread_create(&thr, NULL, &print_hello(a), NULL))
{
printf("Could not create thread\n");
return -1;
}
....
return 0;
}
void * print_hello(int a, void *arg)
{
printf("Hello world and %d!\n", a);
return NULL;
}


Now I get this error:

too few arguments to function print_hello


So how can I fix that?

Answer

pthread passes one argument of type void * to thread function, So you can pass a pointer to any type of data that you want as fourth argument of pthread_create function, look at the example below that fixes your code.

void * print_hello(void *);
int main(int argc, char **argv)
{
    pthread_t thr;
    int a = 10;
    if(pthread_create(&thr, NULL, &print_hello, (void *)&a))
    {
        printf("Could not create thread\n");
        return -1;
    }
    ....
    return 0;
}

void * print_hello(void *arg)
{
    int a = (int)*arg;
    printf("Hello world and %d!\n", a);
    return NULL;
}