Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing more than one parameter to pthread_create [duplicate]

Possible Duplicate:
Multiple arguments to function called by pthread_create()?
How to pass more than one value as an argument to a thread in C?

I have these structures:

struct Request {
    char buf[MAXLENREQ];
    char inf[MAXLENREQ]; /* buffer per richiesta INF */
    int lenreq;
    uint16_t port; /* porta server */
    struct in_addr serveraddr; /* ip server sockaddr_in */
    char path[MAXLENPATH];
    /*struct Range range;*/
};

struct RequestGet {
    char buf[MAXLENREQ];
    int maxconnect;
    struct Range range;
};

struct ResponseGet{
    char buf[MAXLENDATA];
    //int LenRange;
    int expire;
    char dati[MAXLENDATA];
    struct Range range; 
};

How can I pass them to pthread_create? No matter about the meanings of each field of structures.

pthread_create(&id,NULL,thread_func,????HERE????);
like image 632
rschirin Avatar asked Jan 23 '26 06:01

rschirin


1 Answers

You can only pass one parameter, so you generally need to make a function that takes one parameter, even if it just wraps some other calls. You can do this by creating a struct and having the function take a pointer to such a struct.

A basic example to illustrate the point is below. Please note that it is not a complete example, and should not be used as-is! Note, for example, that none of the memory allocated with malloc() is freed.

struct RequestWrapper {
    struct Request *request;
    struct RequestGet *request_get;
    struct ResponseGet *response_get;
};

void thread_func(struct RequestWrapper *rw) {
    // function body here
}

int main(int argc, char *argv[]) {
    struct Request *request = malloc(sizeof(*request));
    struct RequestGet *request_get = malloc(sizeof(*request_get));
    struct ResponseGet *response_get = malloc(sizeof(*response_get));
    ...

    struct RequestWrapper *wrapper = malloc(sizeof(*wrapper));

    wrapper->request = request;
    wrapper->request_get = request_get;
    wrapper->response_get = response_get;

    ...

    pthread_create(&id, NULL, thread_func, &wrapper);
    ...
}
like image 90
Dan Fego Avatar answered Jan 25 '26 20:01

Dan Fego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!