问题
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????);
回答1:
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);
...
}
回答2:
struct Foo {
// anything you want
};
void run (void * _arg) {
Foo * arg = (Foo*) _arg;
// ...
}
int main () {
pthread_t thread;
Foo * foo = create_argument ();
pthread_create (&thread, NULL, run, foo);
}
This depends, of course, on a contract that run will always be given a Foo* in the last argument to pthread_create.
回答3:
The last argument of pthread_create() is a void pointer. Its designation is that you can let it point to whatever kind of variable, struct etc. Your thread_func knows how to handle it and can cast it back to its original type.
回答4:
Put their addresses into a struct, and pass a pointer to that struct as the last argument to pthread_create().
回答5:
you can just create a structure for all data and pass the address of the structure. you may need to put the structure in the heap and free it when done.
来源:https://stackoverflow.com/questions/8976419/passing-more-than-one-parameter-to-pthread-create