简体   繁体   中英

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;
}

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM