PMH
PMH

Reputation: 143

How to pass function pointer that has arguments as an argument of another function?

As you see, I want to pass function send_message to pthread_create, but I don't know how to pass its argument. How to do so?

pthread_create(&t_write, NULL, send_message, NULL); // how to specify argument of the send_message?

void *send_message(void *sockfd){

    char buf[MAXLEN];
    int *fd = (int *)sockfd;
    fgets(buf, sizeof buf, stdin);

    if(send(*fd, buf, sizeof buf, 0) == -1){
        printf("cannot send message to socket %i\n", *fd);
        return (void *)1;
    }

    return NULL;
}

Upvotes: 1

Views: 222

Answers (1)

abligh
abligh

Reputation: 25219

Short answer: simply pass the argument as the fourth parameter to pthread_create.

Longer answer: pthread_create is (per the man page) defined like this:

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

What the third parameter means can be decoded with cdecl:

cdecl> explain void *(*start_routine) (void *)
declare start_routine as pointer to function (pointer to void) returning pointer to void

As you can see, it expects a pointer to a function which takes a void * and returns a void *. Fortunately that's exactly what you have. And per the man page of pthread_create:

The new thread starts execution by invoking start_routine(); arg is passed as the sole argument of start_routine().

Upvotes: 1

Related Questions