Question

We know that we call pthread like this:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
                    void *(*start_routine) (void *), void* arg);

Hi guys, i want to know why the return type of third parameter is void*? why not void?

Was it helpful?

Solution

Because there is no way for a start function to know what kind of data a developer wants to return from the function they use a void* that can point to any type. It is up to the developer of the start function to then cast the void* to appropriate type he actually returned before using whatever the void* points to. So now the start function can return a pointer that may in actually point to anything. If the start function is declared to return void, it means this function returns nothing, then what if the developer wants the start function to return a int, a struct? For example:

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

struct test {
    char str[32];
    int x;
};

void *func(void*) {
    struct test *eg = (struct test *)malloc(sizeof(struct test));
    strcpy(eg->str,"hello world");
    eg->x = 42;
    pthread_exit(eg);
}


int main (void) {
    pthread_t id;
    struct test *resp;

    pthread_create(&id, NULL, func, NULL);
    pthread_join(id,(void**)&resp);

    printf("%s %d\n",resp->str,resp->x);

    free(resp);

    return 0;
}

More details on this post: What does void* mean and how to use it?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top